I have a doubt regarding the size of the derived class. PROBLEM.....
Let A be a base class of size 12 bytes and B be one of it's derived class.Let B's size be 10 bytes.Let an object ob of type B be created
To tell you the truth I thought so(derived class would have a less size than its base class)I didint't took into consideration the fact that the public member along with the protected members will also be accessible to the derived class but that's not what I asked ::::
1 2 3 4 5 6 7 8 9 10
char nkh; // private member......
class b:public a
here nkh is a private member of the base class it cannot be accessed by the derived class anyway...But the size of derived class is still 22(I checked it out thanks Catfish4).Why is this so.....
nb::I am new to this topic.PLEASE FORGIVE ME if I am wrong :))
Because you can have friend function which have access to private part. Or you could do some pointer magic and access it anyway. Or it can hold some magic number used to find it in binary stream. Or something else.
You can make sure that a derived class can not have a size less than the size of its base class executing this simple statement for your example
std::cout << "sizeof( a ) = " << sizeof( a ) << ", sizeof( b ) = " << sizeof( b )
Any object of a derived class contains all members of its base class. Moreover even when a member function of a base class is private nevertheless it is considered in the function overload resolution for the derived class (if of course its name was placed in the derived class scope with a using declaration).
It seems that I am wrong. There is a situation when the size of a base class can be greater than the size of its derived class. It is the situation when the base class is empty that is when it has no data members or virtual functions. In this case if I am not mistaken the size of the base class can be equal to any non-zero value. IF a derived class contains one data member that has the size that is less than the size of th base class then the size of the derived class itself can be less than the size of the base class. For example empty base class can have size equal to 8 while its derived class with one member of type int can have size equal to 4.