问题
What is the difference between a sub-object and a contained object? For constructing an instance of a class which is derived from another class, first the sub-object has to be created and then the derived object has to be created.
Questions:
Is it true that derived object contains the sub-object?
How can one visualize the difference in the structure of an object
a) which contains another object
b) which is derived from another class
Do the objects in a) and b) have the same structure ?
回答1:
Yes, derived object contains instances of its base class subobjects.
Physically there's really no difference between containing an object (as a member) and deriving from an object. Moreover, the language refers to both as subobjects: base class subobjects and member subobjects.
Virtual inheritance typically introduces some additional household data, which makes it more complicated than just "containing" a base subobject, but ordinary inheritance usually just boils down to plain "containment".
The difference between deriving and containing as member really exists only on conceptual level. Different access syntax, different features. For example, derivation in involved into such language features as polymorphism.
回答2:
In C++ the difference is in virtual methods. Derived class can redefine base subobject virtual methods. Contained object is as it is. This is more or less what Kirill answered - but I hope a little simpler answer.
回答3:
Yes, derived object contains the subobject. It would not be wrong to say so. Although the derivation is a little bit more. Data members and methods can be accessed directly. Virtual functions take slots in the VMT. All this does not happen when the object is contained.
Visualizing the difference. There is no commonly accepted way of doing this. From the memory layout point of view the difference is in VMTs. Contained object has its own VMT field (if it has one). Derived object has its own VMT that is created out of the VMT of the base object by adding new entries and replacing some.
来源:https://stackoverflow.com/questions/11427439/difference-between-sub-object-and-contained-object