I'm trying to understand the affect of inheritance order in C++.. I looked online, but I couldn't find a clear and sufficient answer...
So, for the sake of the question, assume there are 2 classes: class B and class C.
Now, define:
class A1 : public B, public C{ ... }; class A2 : public C, public B{ ... };
What is the difference between A1 and A2?
Thanks a lot!
The order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6. 2), cleanup (12.4), and storage layout (9.2, 11.1). Constructors are called in the order you write them down (first base class in the list is constructed first) (§12.6.
In Multiple inheritance, one class can have more than one superclass and inherit features from all its parent classes. As shown in the below diagram, class C inherits the features of class A and B. But C# does not support multiple class inheritance.
The order of construction depends on the sequence of inheritance. Initialization order doesn't matter.
Multiple Inheritance in C++Multiple inheritance occurs when a class inherits from more than one base class. So the class can inherit features from multiple base classes using multiple inheritance. This is an important feature of object oriented programming languages such as C++.
The C++11 Standard says (§10.1) [class.mi]:
The order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1).
The three referenced paragraphs reveal that
Note that the memory layout can be important. For example, if an external library makes naive C-style casts that assume that the part of the object it's interested in is at the beginning, it can lead to run time errors that are hard to debug.
The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.
The order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1). — end note ]" (§10.1/2)
From IBM's C++ documentation: Multiple inheritance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With