Reputation: 16091
I guess the topic is all I need to ask. A little explanation around the topic would be nice. Please clear some questions like why or why not?
Example:
class A {
private:
int a;
};
class B : A {
int b;
};
int main (int argc, char **argv) {
B *p = new B(); // Does this allocate memory for a?
}
Upvotes: 3
Views: 767
Reputation: 153830
It depends on what you mean with allocate: it does not do a heap allocation or something. A derived object will contain the members inherited from the base. That is all base classes of a derived class can be seen as subobjects. The derived class objects will contain all these subobjects and will also make sure that they are properly constructed/destructed.
Upvotes: 2
Reputation: 517
Yes it will allocate memory for A also.
Because when you inherit a class
from another class and when you create the object
of derived class, Complier will allocate memory equal to size of derived class+base class,so that there would be no loss of data.
As base class members
are also accessible from derived class.
Upvotes: 1
Reputation: 254461
Yes. A class object contains all of its direct non-static data members, and those of any base-class sub-objects. Access specifiers make no difference; they merely restrict where names can be used.
Upvotes: 6