In C++, when a class inherits other class, if I create an object for the subclass, then will the subclass object create memory for all data members and member functions for the superclass, too?
+6
A:
Yep (though the member functions per se don't need memory... vtables are another issue, and are per-class and not per-instance anyway) -- an instance of the subclass "embeds", if you will, one of the superclass. Say all instance variables are 32-bit ints for simplicity: if the superclass has 3 and the subclass adds 2 more, then each instance of the subclass will allocate 5 x 4 = 20 bytes -- 8 for its own instance variables, plus 12 for the instance variables of the superclass. (Plus 4 bytes for a vtable pointer iff there are any virtual methods in play).
So, what's the question...?
Alex Martelli
2009-07-28 04:58:27