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 typeBase*. - 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 aDerivedobject, its dynamic type isDerived.- 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)#
| Direction | Target Form | Conversion Method & Validity | Dynamic Type & Runtime Behavior |
|---|---|---|---|
| Upcast Base ← Derived | Pointer / ReferenceBase*, Base& | ✅ Implicit conversion | Preserves Dynamic Type DerivedDynamic binding invokes Derived’s overridden virtual functions. |
| Upcast Base ← Derived | Object — by valueBase | ⚠️ Valid syntax, but invokes Base copy constructor only | Object Slicing occursDerived members and dynamic type info are sliced off, leaving a plain Base object. |
| Downcast Derived ← Base | Pointer / Referencedynamic_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 function | Verifies at runtime via RTTI whether the target is Derived:
|
| Downcast Derived ← Base | Object — by valueDerived | ❌ Compile error | A Base object does not contain Derived member storage, so value-object downcasting is impossible. |
- Why Does
dynamic_castRequire at Least OnevirtualFunction? —vptr/vtableand 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
virtualfunction: The compiler inserts a hidden pointervptrat the start of each object, pointing to a sharedvtablethat stores both virtual function addresses and RTTI metadata (std::type_infoand inheritance graph info). - Because
dynamic_casttraversesvptr→vtable→ RTTI at runtime to verify the dynamic type, attemptingdynamic_caston a class withoutvirtualfunctions is a compile error.
- Non-polymorphic class without
#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#
- Downcast (
Derived*←Base*,Derived&←Base&): The most common use. Pointer casts returnnullptron failure; reference casts throwstd::bad_cast. - Crosscast (
BaseB*←BaseA*): Under multiple inheritance, converts across two unrelated co-inheritedBaseclasses of the same derived object — impossible withstatic_cast, and resolved at runtime via RTTI. dynamic_cast<void*>(BASE_PTR): Obtains the starting memory address of the most-derived object, regardless of whichBase*subobject pointer you currently hold.- 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 concreteBasevalue container is syntactically legal, inserting aDerivedobject causes Object Slicing, stripping away theDerivedpart 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/eraserequire rebinding slots to different targets and default-constructing slots onresize, whereas references cannot be rebound after initialization or default-constructed. Usestd::vector<std::reference_wrapper<Base>>— a copyable, rebindable pointer wrapper — when reference semantics are desired.
- Language rule: References are aliases rather than objects, so C++ forbids arrays of references (
- 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>>orstd::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.
- Owning container (heap-allocated objects): Use
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 notvirtual, the compiler uses the static type (Base*) and runs only~Base(), leakingDerived’s resources and causing Undefined Behavior. - Therefore, every root base class in an inheritance hierarchy must define a
virtualdestructor (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:
Baseconstructor runs first →Derivedmembers 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#
- Conditions for Dynamic Binding & Name Hiding When
virtualIs 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 inDeriveddoes not override it, and addingoverrideis a compile error; it merely performs Name Hiding. Calling it through aBase*pointer resolves statically to theBaseversion regardless of the runtime object type:
- The called member function must be declared
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)
}- What Happens When
overrideIs Omitted:- When the signature matches exactly: Once a function is declared
virtualinBase, it remainsvirtualin derived classes even if bothvirtualandoverrideare omitted, so overriding still takes effect. However, if theBasesignature is later modified, the compiler will not catch the mismatch. - When parameter types or
constqualifiers differ: Withoutoverride, a signature mismatch compiles silently without error and declares a separate new function + Name Hiding instead of overriding. Calls throughBase*orBase&then unexpectedly invoke theBaseversion at runtime — always mark every intended override withoverrideso mismatches become immediate compile errors:
- When the signature matches exactly: Once a function is declared
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...). OmittingBASE::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
protectedis to keep members hidden likeprivatefrom external users while opening access to derived classes. Meanwhile,friendalways operates at the same access level as the member functions of whichever class declared thatfriend. - Important Restriction:
Derivedmay access the base class’sprotectedmembers only through theBasesubobject embedded inside aDerivedobject. As shown below, it has no special access toprotectedmembers of an independent standaloneBaseobject:
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
Derivedobject still physically contains theBaseclass’sprivatedata members inside its embeddedBasesubobject. - No direct access: Even inside
Derived’s own member functions,Base’sprivatemembers cannot be read or modified directly by name; they must be initialized and manipulated indirectly throughBase’s constructors andpublic/protectedmember 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.