why size of *this and size of basic and derived class different?

B

Bob

Try the following code
class basic
{
public:
virtual void one()=0;
};

class derived1:public basic
{
public:
virtual void two()=0;
};

class derived2:pubilc base
{
public:
virtual void three()=0;
};

class component : public derived,public derived2
{
public:
void one(){ cout<<sizeof(*this);}
void two(){cout<<sizeof(*this);}
void three(){cout<<sizeof(*this);}




};

void main()
{
//
basic * b = (derived1*)new component;
cout<<*b;
b->one();

}

My question is why size of *b and size of *this are different.
sizeof(*b) will give the size of the base class (4)while
sizeof(*this)gives the size of component class(8) although the pointer
used here is *b i.e basic class pointer.

regards,
Bob
 
J

John Harrison

Bob said:
Try the following code
class basic
{
public:
virtual void one()=0;
};

class derived1:public basic
{
public:
virtual void two()=0;
};

class derived2:pubilc base
{
public:
virtual void three()=0;
};

class component : public derived,public derived2
{
public:
void one(){ cout<<sizeof(*this);}
void two(){cout<<sizeof(*this);}
void three(){cout<<sizeof(*this);}




};

void main()
{
//
basic * b = (derived1*)new component;
cout<<*b;

I guess you mean

cout<<sizeof(*b);
b->one();

}

My question is why size of *b and size of *this are different.
sizeof(*b) will give the size of the base class (4)while
sizeof(*this)gives the size of component class(8) although the pointer
used here is *b i.e basic class pointer.

That's not right, the method one() is in the Component class so 'this' has
type Component*, therefore sizeof(*this) equals sizeof(Component).

Not sure why you think it would be any different, but remember that sizeof
is worked out at compile time. The number printed by the method one() will
always be the same no matter what pointer is used to call it.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top