Object-Oriented Programming (OOP)#

Based on C++ Primer, 5th ed., Chapter 15: Object-Oriented Programming and Section 19.2.1: dynamic_cast, this post summarizes the three pillars of OOP, Upcast / Downcast, Object Slicing, and Polymorphic Containers, Virtual Functions (virtual, override, final), Pure Virtual Functions (= 0) and Abstract Base Classes, and access control under inheritance.

1. The Three Pillars of OOP#

Object-oriented programming is built on three core principles:

  • Data Abstraction: Define classes that separate interface from implementation. — see Classes
  • Inheritance: Define classes that model the relationships among similar types.
  • Dynamic Binding: Use objects of derived types while ignoring the details of how they differ.

2. Upcast vs. Downcast and Static vs. Dynamic Type#

Expressions dealing with polymorphic types distinguish between two types:

  • Static Type: The type of a variable or expression known at compile time from its declaration — e.g., a Base* pointer variable always has static type Base*.
  • Dynamic Type: The type of the actual object in memory that a pointer or reference denotes at runtime — e.g., if a Base* pointer points to a Derived object, its dynamic type is Derived.
    • For a value object variable (neither pointer nor reference), its static type and dynamic type are always identical.

1. Upcast (Base ← Derived) vs. Downcast (Derived ← Base)#

DirectionTarget FormConversion Method & ValidityDynamic Type & Runtime Behavior
Upcast
Base ← Derived
Pointer / Reference
Base*, Base&
✅ Implicit conversionPreserves Dynamic Type Derived
Dynamic binding invokes Derived’s overridden virtual functions.
Upcast
Base ← Derived
Object — by value
Base
⚠️ Valid syntax, but invokes Base copy constructor onlyObject Slicing occurs
Derived members and dynamic type info are sliced off, leaving a plain Base object.
Downcast
Derived ← Base
Pointer / Reference
dynamic_cast<Derived*>(BASE_PTR)
dynamic_cast<Derived&>(BASE_REF)
✅ Use dynamic_cast when Base has at least one virtual function — compile error without a virtual functionVerifies at runtime via RTTI whether the target is Derived:
  • Success: returns Derived* / Derived&
  • Pointer failure: returns nullptr
  • Reference failure: since a reference cannot be null, throws std::bad_cast
Downcast
Derived ← Base
Object — by value
Derived
❌ Compile errorA Base object does not contain Derived member storage, so value-object downcasting is impossible.
  • Why Does dynamic_cast Require at Least One virtual Function? — vptr / vtable and RTTI (Run-Time Type Identification):
    • Non-polymorphic class without virtual: Under C++’s Zero-Overhead principle, only data members are laid out in memory with no hidden object header — at runtime, no type tag exists in memory at all.
    • Polymorphic class with at least one virtual function: The compiler inserts a hidden pointer vptr at the start of each object, pointing to a shared vtable that stores both virtual function addresses and RTTI metadata (std::type_info and inheritance graph info).
    • Because dynamic_cast traverses vptr → vtable → RTTI at runtime to verify the dynamic type, attempting dynamic_cast on a class without virtual functions is a compile error.
#include <iostream>
#include <typeinfo> // std::bad_cast

class Base {
public:
  virtual ~Base() = default;
  virtual void speak() const { std::cout << "Base\n"; }
};

class Derived : public Base {
public:
  int extra_data = 42;
  void speak() const override { std::cout << "Derived\n"; }
};

void cast_examples() {
  Derived d;

  // 1. Upcast (Pointer / Reference): Implicit conversion + preserves Dynamic Type + Dynamic Binding works!
  Base *bp = &d;
  Base &br = d;
  bp->speak(); // Prints "Derived" (Dynamic Binding)
  br.speak();  // Prints "Derived" (Dynamic Binding)

  // 2. Upcast (Object): "Slice Down" (Object Slicing) -> loses Dynamic Type info!
  Base sliced = d; // Derived::extra_data is sliced off; only Base subobject is copied
  sliced.speak();  // Prints "Base" (sliced is purely a Base object)

  // 3. Downcast (Pointer): dynamic_cast -> returns nullptr on failure
  if (Derived *dp = dynamic_cast<Derived*>(bp)) {
    std::cout << dp->extra_data << "\n"; // Succeeds: bp actually points to Derived(d)
  }
  Base plain_base;
  Base *bp2 = &plain_base;
  Derived *dp_fail = dynamic_cast<Derived*>(bp2); // Fails! dp_fail == nullptr

  // 4. Downcast (Reference): dynamic_cast -> throws std::bad_cast on failure
  try {
    Derived &dr_fail = dynamic_cast<Derived&>(*bp2);
  } catch (const std::bad_cast &e) {
    std::cout << "Downcast failed: " << e.what() << "\n";
  }

  // 5. Downcast (Object): Impossible!
  // Derived d2 = plain_base; // Compile error!
}

2. Scope of dynamic_cast#

  1. Downcast (Derived* ← Base*, Derived& ← Base&): The most common use. Pointer casts return nullptr on failure; reference casts throw std::bad_cast.
  2. Crosscast (BaseB* ← BaseA*): Under multiple inheritance, converts across two unrelated co-inherited Base classes of the same derived object — impossible with static_cast, and resolved at runtime via RTTI.
  3. dynamic_cast<void*>(BASE_PTR): Obtains the starting memory address of the most-derived object, regardless of which Base* subobject pointer you currently hold.
  4. Upcast (Base* ← Derived*): Syntactically allowed, but resolved at compile time identically to an implicit conversion and unnecessary in practice.
// Crosscast and dynamic_cast<void*> under multiple inheritance (across co-inherited bases: Serializable* <- Printable*)
class Printable { public: virtual ~Printable() = default; };
class Serializable { public: virtual ~Serializable() = default; };
class Document : public Printable, public Serializable {};

Printable *p = new Document();
// Printable and Serializable have no parent-child relationship, yet succeed because *p is a Document!
if (Serializable *s = dynamic_cast<Serializable*>(p)) {
  // Obtains pointer to Document's Serializable subobject
  void *most_derived = dynamic_cast<void*>(s); // Returns starting address of the full Document object
}
delete p;

3. Store Pointers to Use Dynamic Binding in Containers#

  • Storing by value causes Object Slicing (std::vector<Base>): Although storing into a concrete Base value container is syntactically legal, inserting a Derived object causes Object Slicing, stripping away the Derived part so Dynamic Binding does not work.
  • No direct reference containers (std::vector<Base&> — compile error):
    • Language rule: References are aliases rather than objects, so C++ forbids arrays of references (Base&[]) and pointers to references (Base&*, required internally by container allocators).
    • Container operation constraints: Reallocation and element shifts during insert / erase require rebinding slots to different targets and default-constructing slots on resize, whereas references cannot be rebound after initialization or default-constructed. Use std::vector<std::reference_wrapper<Base>> — a copyable, rebindable pointer wrapper — when reference semantics are desired.
  • Pointer choice by ownership: Indirection through either smart pointers or raw pointers equally preserves Dynamic Type and Dynamic Binding.
    • Owning container (heap-allocated objects): Use std::vector<std::unique_ptr<Base>> or std::vector<std::shared_ptr<Base>> for automatic cleanup on destruction or exceptions.
    • Non-owning observer container: Use std::vector<Base*> when merely referencing objects whose lifetimes are already managed elsewhere, such as on the stack or in another owner container.

3. Essential Design Rules for Base and Derived Classes#

1. Base Classes Must Define a virtual Destructor (virtual ~Base())#

  • When deleting a dynamically allocated derived object through a base pointer (Base *p = new Derived(); delete p;), if ~Base() is not virtual, the compiler uses the static type (Base*) and runs only ~Base(), leaking Derived’s resources and causing Undefined Behavior.
  • Therefore, every root base class in an inheritance hierarchy must define a virtual destructor (virtual ~Base()).

2. Derived Constructors Initialize Base Subobjects via the Base Constructor#

  • A derived constructor cannot directly initialize base-class data members in its member initializer list. Instead, it must invoke the base-class constructor to initialize its base subobject first.
  • Construction Order: Base constructor runs first → Derived members and constructor body run second.
  • Destruction Order — Reverse of Construction: ~Derived() runs first → ~Base() runs second.
class Quote {
public:
  Quote() = default;
  Quote(const std::string &book, double sales_price)
      : bookNo(book), price(sales_price) {}

  std::string isbn() const { return bookNo; }
  virtual double net_price(std::size_t n) const { return n * price; }
  virtual ~Quote() = default; // Essential! Virtual destructor for polymorphic deletion

private:
  std::string bookNo;
protected:
  double price = 0.0;         // Accessible to derived classes
};

class Bulk_quote : public Quote {
public:
  Bulk_quote() = default;
  // Delegate initialization of base members (bookNo, price) to the Quote constructor!
  Bulk_quote(const std::string &book, double p, std::size_t qty, double disc)
      : Quote(book, p), min_qty(qty), discount(disc) {}

  double net_price(std::size_t cnt) const override {
    if (cnt >= min_qty) return cnt * (1 - discount) * price;
    return cnt * price;
  }
private:
  std::size_t min_qty = 0;
  double discount = 0.0;
};

4. Virtual Functions and Abstract Base Class Rules#

For a summary table of the virtual, = 0 (pure virtual), override, and final keywords, see C++ Keywords Reference: Inheritance & Polymorphism (OOP) Keywords.

1. virtual & override keyword#

  1. Conditions for Dynamic Binding & Name Hiding When virtual Is Omitted:
    • The called member function must be declared virtual, and the call must be made through a pointer or reference. Calling on a value object resolves statically at compile time.
    • If a base member function is not declared virtual, defining a same-named function in Derived does not override it, and adding override is a compile error; it merely performs Name Hiding. Calling it through a Base* pointer resolves statically to the Base version regardless of the runtime object type:
class Base {
public:
  virtual ~Base() = default;
  void non_virt() const { std::cout << "Base::non_virt\n"; }         // NOT virtual
  virtual void virt() const { std::cout << "Base::virt\n"; }         // virtual
};

class Derived : public Base {
public:
  // void non_virt() const override {}                               // ❌ Compile error! Base function is not virtual
  void non_virt() const { std::cout << "Derived::non_virt\n"; }      // ⚠️ Name Hiding, NOT overriding
  void virt() const override { std::cout << "Derived::virt\n"; }     // ✅ Valid override
};

void binding_demo() {
  Derived d;
  Base *ptr = &d;       // Dynamic Type is Derived, while the pointer's Static Type is Base*
  ptr->non_virt();      // 💥 Prints "Base::non_virt"! (Non-virtual: follows Static Type Base*)
  ptr->virt();          // ✅ Prints "Derived::virt"! (Dynamic Binding)
}
  1. What Happens When override Is Omitted:
    • When the signature matches exactly: Once a function is declared virtual in Base, it remains virtual in derived classes even if both virtual and override are omitted, so overriding still takes effect. However, if the Base signature is later modified, the compiler will not catch the mismatch.
    • When parameter types or const qualifiers differ: Without override, a signature mismatch compiles silently without error and declares a separate new function + Name Hiding instead of overriding. Calls through Base* or Base& then unexpectedly invoke the Base version at runtime — always mark every intended override with override so mismatches become immediate compile errors:
class Base {
public:
  virtual ~Base() = default;
  virtual void process(int x) const { std::cout << "Base::process\n"; }
};

class Derived : public Base {
public:
  // 1) Exact signature match still overrides even without 'override' (discouraged)
  // void process(int x) const { std::cout << "Derived::process\n"; }

  // 2) Accidentally omitted 'const' AND omitted 'override':
  void process(int x) { std::cout << "Derived::process\n"; } // ⚠️ Compiles silently as a separate function + Name Hiding!
  // void process(int x) override; // ❌ With 'override', the missing 'const' is caught immediately at compile time!
};

void override_pitfall() {
  Derived d;
  const Base &br = d;
  br.process(10); // 💥 Prints "Base::process"! Derived::process did not override due to missing const
}

2. Virtual Functions and Default Arguments Pitfall#

  • When a virtual function call uses a default argument, the value is determined at compile time by the static type of the pointer or reference, not the dynamic type. Always give base and derived overrides identical default arguments.

3. Circumventing the Virtual Mechanism (BASE::FUNC())#

  • When a derived virtual function needs to call its base-class version, it must qualify the call with the scope operator: BASE::FUNC(ARGS...). Omitting BASE:: causes dynamic binding to resolve back to the derived function itself, resulting in infinite recursion.

5. Access Control Under Inheritance (protected, private, friend)#

For the public, protected, and private access table and derivation access specifier rules, see Classes: Access Control.

1. protected Access Specifier#

  • The purpose of protected is to keep members hidden like private from external users while opening access to derived classes. Meanwhile, friend always operates at the same access level as the member functions of whichever class declared that friend.
  • Important Restriction: Derived may access the base class’s protected members only through the Base subobject embedded inside a Derived object. As shown below, it has no special access to protected members of an independent standalone Base object:
class Base {
protected:
  int prot_mem = 0;
};

class Derived : public Base {
  void test(Derived &d, Base &b) {
    d.prot_mem = 10;    // ✅ OK: accessed through the Base subobject inside Derived object d
    // b.prot_mem = 20; // ❌ Compile error: cannot access protected member on standalone Base object b!
  }
};

2. private Access Specifier#

  • Present in memory: Every Derived object still physically contains the Base class’s private data members inside its embedded Base subobject.
  • No direct access: Even inside Derived’s own member functions, Base’s private members cannot be read or modified directly by name; they must be initialized and manipulated indirectly through Base’s constructors and public / protected member functions.

3. Friendship Is Not Inherited (friend)#

  • Friends of a base class have no special access to members of its derived classes, and derived classes have no special access to classes that grant friendship to the base class.