Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help about inheritance and this pointer

Status
Not open for further replies.

neoreturned

Programmer
Apr 25, 2006
9
TR
hi everyone i hav a porgram and it is uses streams and files also inheritances....

//////////////////////
.
.
.

class base{
protected:
int a;
int b;
public:
void getdata()
{}

void FileWrite(const char* filename,int no)
{
ofstream dos(filename,ios::binary|ios::app);
dos.seekp(no*sizeof(*this));
dos.write((char*)this,sizeof(*this));
}
};
.
.
.
class derived:public base
{
private:
int c;
public:
void FileWrite(const char* filename,int no)
{
base::FileWrite(filename,no);
}
};
.
.
.
int main()
{
derived* derobj=new derobj;

derobj->getdata();
derobj->FileWrite("FILE.DAT",0);
}


In this program derived's class FileWrite function sees this pointer as derived object and sizeof(*this)=12...(sizeof(int)=4). But base::FileWrite() function sees this derived object but sizeof(*this)=8...
and it only see base datas not derived(in this int c is derived's data...)

What is wrong and how can i fix this problem????





 
There is no problem. That's how it's supposed to work. base has 2 ints (2 x 4 bytes), and derived has 3 ints (3 x 4 bytes). base can never see data in derived classes; what would be the point?
 
void FileWrite(const char* filename,int no)
{
base::FileWrite(filename,no);
}
derobj call derived class's FileWrite() so 'this' is derobj's address

in this program when we enter base::FileWrite(filename,no);
line this shows derobj->a,derobj->b but not derobj->c it is the porblem why NOT derobh->c
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top