Question

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:

  1. Is it true that derived object contains the sub-object?

  2. 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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top