<<< Inheritance and friendship     Index     Inheritance vs. templates >>>

17. Inheritance vs. encapsulation

  • There are two ways to be a client of an existing class A:

    • Inherit from type A

    • Have a member of type A

  • Inheritance automatically provides interface of Base class.

  • Encapsulation allows restricting the interface, but requires republication of needed parts.

  • Usually, it's pretty obvious which is correct.

  • Class libraries often rely on inheritance (recall Printer example.)

  • This is known as Is-a vs. Has-a:

      class Employee (Base)
               | |
               | +--has-a--> int Salary;
               | `--has-a--> string Name;
               |
               |
               |
      class Manager (Derived) : (is-a) public Employee
                 |
                 `--has-a--> Employee subordinates[ 10 ];
    
<<< Inheritance and friendship     Index     Inheritance vs. templates >>>