Other Inheritance Issues
Notes
-
class DerivedIdT: [access-specifier] BaseIdT
- if the access-specifier is missing, the access is public
- Private inheritance
- All public and protected members of the base class are now private members of the derived class.
- This is useful at a higher level design concepts
- One of these is composition.
- But Gregorie suggests that this might not be well known, so advises against it.
- I would avoid it until you become more skilled at inheritance.
- Protected is very strange
- All public and protected members of the base become protected in the derived class.
- Very few places give concrete reasons for this.
- I would avoid it until you become more skilled at inheritance.
- Virtual
-
class DerivedIdT : virtual public BaseIdT {
- We will explore this later
- But it marks the base class as virtual.
- And the most derived object contains only one instance of this base class.
- This is used in multiple inheritance as a solution to the diamond problem.
- Multiple Inheritance
-
class DerivedIdT: public BaseA, public BaseB, ...{
- The derived class will inherit from all listed classes.
- This is not bad, unless any ancestor is shared, then we have the diamond problem.
- The diamond problem
- We have a PlayerT
- From that is derived a FighterT and a WizardT
- Both have the members of the base class.
- From both of these classes we derive the FighterWizardT
- Unless the base classes are marked virtual, the FighterWizardT will contain two copies of the PlayerT members.
- This will lead to all kinds of ambiguities when trying to build the code because of multiple versions of base class member functions.
- And it will cause problems with multiple different versions of base class member variables, with multiple different values.
- See diamond1.cpp and diamond2.cpp.