COMS W4995 C++ Deep Dive for C Programmers

Inheritance

Lecture Outline

inherit1

  1. Inheritance basics

    • default member initializer
    • B::sum() - invoking the base class’s member function
    • w() macros for convenience
    • protected access modifier
  2. Memory layout of derived classes

    • reinterpret_cast
  3. Static vs. dynamic binding

    • Pointer or reference to B can bind to a D object
    • Static binding by default unlike Java

    • Dynamic binding requries “virtual” function specifier:

        virtual uint64_t sum() const { return b; }
      
    • “override” specifier ensures that the function is virtual and is overriding a virtual function from a base class:

        uint64_t sum() const override { return B::sum() + d; }
      
  4. Virtual function table (vtable)

    • Object size & layout changes when it contains virtual functions
    • Diagram of vtable and vtable pointer
    • Calling a virtual function manually

inherit2

  1. Multiple inheritance object layout

    • Multiple inheritance diagram
  2. Base pointers have different addresses

    • The compiler must change the memory addresses of base-type pointers to the same multiply derived object in order for the base-type pointers to point to the right part of the object.
  3. static_cast

  4. Multiple inheritance with virtual functions

    • pb->sum() and pc->sum() polymorphically invoke D::sum()

    • Two vptrs are added to the object

  5. dynamic_cast

  6. (Optional) vtable layout

inherit3

  1. The diamond problem: D object contains two A portions

  2. Base classes B & C still behave the same

  3. But referring to the base class A is ambiguous

inherit4

  1. Virtual inheritance fixes the diamond problem

  2. sum() behaves polymorphically via any base pointer

  3. (Optional) D’s vtable layout

inherit5

  1. Order of initialization: base classes, data members, constructor body

    • Note the base class initialization syntaxt: B{100}

    • Destructors are called in the opposite order

  2. Pure virtual function & abstract class

  3. Virtual destructor