size of object in publically inherited class

hardik31385's Avatar, Join Date: Mar 2009
Newbie Member
hello Experts ,
i am conduced in following program output..
Code:
#include<iostream.h>
#include<conio.h>
class base
{
    int i;
};
class derived1:base
{
    int j;
};
class derived2:base
{
    int k;
};
class derived3:derived1,derived2
{
    int l;
};
void main()
{
    clrscr();
    derived3 a;
    cout<<sizeof(a);


    getch();

}
i m getting output 10 ...but how it is possible as hear public data member's , and class is inherited as public , how it is possible to inherit private member?

Last edited by shabbir; 31Mar2009 at 07:56.. Reason: Code blocks
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
I guess sizeof int is 2 on your system.
In derived3 you have derived3::l, derived1::j, derived2::k, derived1::base::i and derived2::base::i, which is five int's. Hence 10.
When you derive a class you get the whole lot, private or otherwise.
hardik31385's Avatar, Join Date: Mar 2009
Newbie Member
Quote:
Originally Posted by xpi0t0s View Post
I guess sizeof int is 2 on your system.
In derived3 you have derived3::l, derived1::j, derived2::k, derived1::base::i and derived2::base::i, which is five int's. Hence 10.
When you derive a class you get the whole lot, private or otherwise.
I think you r right , is thr any case of default constructor? because , that program act like that , it will call default constructor , and default constructor , will return sizeof(this) for individual class.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Every class X has a default compiler-provided constructor X::X() which you can override if necessary.
In your example five constructors will be called; two bases, derived1, derived2 and derived3.
Not sure which order it'll be done in or if that order is guaranteed, but you could try adding something like
Code:
class derived2:base
{
    int k;
public:
    derived2() { cout << "In derived2 ctor\n"; }
};
to see what's going on internally.

I'm not sure I understand what you're getting at regarding constructors and sizeof this; there is only one sizeof called and that's sizeof(a). The compiler can determine the size from the code; this isn't determined at runtime.
Mridula's Avatar, Join Date: Mar 2008
Pro contributor
Irrespective of access -specifiers, the sizeof an object is calculated. And it is decided at compile time itself.
Mridula's Avatar, Join Date: Mar 2008
Pro contributor
It is nothing but number of bytes needed to store that particulear object. Though, private members are not accessible to derived, still it would have taken enough space to store it's base classes private variables as part of it's memory-map.