Inheritance
Inheritance
This domain tests deriving classes and reuse. A derived class inherits members from a base class and adds or modifies behaviour. class Dog : public Animal expresses an is-a relationship. Single, multiple, multilevel, hierarchical and hybrid inheritance are recognized; the diamond problem arises in hybrid inheritance and is solved with a virtual base class.
Access rules
- Public inheritance: public members stay public, protected stay protected in the derived class.
- Protected inheritance: public and protected become protected.
- Private inheritance: public and protected become private. Private members of the base are inherited but not directly accessible; use protected or base-class functions. Constructors run base first, then derived; destructors run in reverse.
Worked example
class Animal { public: void eat() { cout << 'A'; } };
class Dog : public Animal { public: void bark() { cout << 'B'; } };
Dog d; d.eat(); d.bark(); is valid because eat is public in the base and public inheritance preserves that. If Animal had a private age, d.age would be invalid, although Dog objects still contain that base part. Construction order: Animal then Dog; destruction: Dog then Animal.
Traps
Default inheritance for a class is private, so class Dog : Animal is not public inheritance. Private base members are not accessible in the derived class. Multiple inheritance can create ambiguity; qualify with the base name. A base pointer can point to a derived object, not the reverse safely.