Inheritance and Polymorphism in C++ Study Notes

Fundamentals of Inheritance in C++

  • Core Definition:

    • Inheritance is a foundational mechanism of Object-Oriented Programming (OOP) wherein a derived class acquires the properties, fields, and behaviors (methods) of an existing base class.
    • It fosters code reusability by allowing developers to extend existing class declarations rather than rewriting boilerplate logic from scratch.
    • It provides structural support for hierarchical class modeling and software modularity.
  • General Syntax:

    • A child class specifies its relationship and access privileges to a parent class using the colon operator (:):
class ChildClass : public ParentClass
{
    // Additional fields and methods
};
  • ChildClass (or Derived Class) represents the specialized entity inheriting state and logic.

  • ParentClass (or Base Class) is the existing entity being extended.

  • accessSpecifier governs the accessibility mode and can be explicitly declared as public, protected, or private.

    • Introductory Implementation Example:
  • The base class Person encapsulates personal identity data, while the derived class Student inherits identity access and adds specific academic data.

#include <iostream>
using namespace std;

// Base Class (Parent)
class Person {
public:
    string name = "Jordan";
    void showIdentity() {
        cout << "Name: " << name << std::endl;
    }
};

// Derived Class (Child)
class Student : public Person {
public:
    int gradeLevel = 10;
};

int main() {
    Student myStudent;
    // Accessing child property
    cout << "Grade Level: " << myStudent.gradeLevel << endl;
    // Accessing inherited property and method from Person
    myStudent.showIdentity();
    return 0;
}
  • Program Output:
    • Grade Level: 10
    • Name: Jordan

Access Modes in Inheritance

  • Public Access Mode (public):

    • When deriving in public mode, public members of the base class remain public in the derived class, and protected members remain protected.
    • Base class members are inherited directly as they are declared.
    • Private members of the base class remain inaccessible directly by the derived class.
  • Private Access Mode (private):

    • All public and protected members of the base class become private members within the derived class.
    • These members are completely hidden from subsequent derived classes down the inheritance hierarchy.
  • Protected Access Mode (protected):

    • Both public and protected members of the base class become protected members inside the derived class.
    • They remain accessible within the derived class and any subsequent derived classes inheriting from it, but remain hidden from external public access.

Types of Inheritance Architectures

  • Taxonomy of Inheritance:

    • Inheritance structures are classified based on the architectural relationship and linkage established between base classes and derived classes:
    • Single Inheritance
    • Multilevel Inheritance
    • Multiple Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
  • 1. Single Inheritance:

    • Definition: A class is allowed to inherit from only one direct base class, creating a simple one-to-one parent-child mapping.
    • Structural Diagram:

Single Inheritance Class Vehicle to Class Car

  • Syntax:
class ChildClass : public ParentClass
{
    // Additional fields and methods
};
  • Code Implementation:
#include <iostream>
using namespace std;

// Base Class (Parent)
class Vehicle {
public:
    int speed = 60;
    void move() {
        cout << "The vehicle glides forward smoothly." << endl;
    }
};

// Derived Class (Child)
class Car : public Vehicle {
public:
    int doors = 4;
};

int main() {
    // Instantiate an object of the Derived Class
    Car myCar;
    cout << "Doors: " << myCar.doors << endl;
    cout << "Speed: " << myCar.speed << " mph" << endl;
    myCar.move();
    return 0;
}
  • Execution Output:

    • Doors: 4

    • Speed: 60 mph

    • The vehicle glides forward smoothly.

    • 2. Multilevel Inheritance:

  • Definition: An inheritance model where a class is derived from another derived class, establishing a multi-tiered inheritance chain.

  • Key Characteristics:

    • Features are inherited sequentially level-by-level.
    • The most derived class acquires access to all accessible members across all ancestor levels in the chain.
    • Accessibility across tiers is determined by the specific access specifiers chosen at each inheritance link.
    • Directly mirrors hierarchical real-world parentage and lineage structures.
  • Structural Diagram:

Multilevel Inheritance Grandfather to Father to Child

  • Syntax:
class A {
    // Base class
};
class B : public A {
    // Derived from A, acts as base for C
};
class C : public B {
    // Derived from B, inherits accessible members of A and B
};
  • Code Implementation:
#include <iostream>
using namespace std;

class Student {
protected:
    int rollNo;
    string name;
public:
    void getStudentDetails(int r, string n) {
        rollNo = r;
        name = n;
    }
    void displayStudentDetails() {
        cout << "Student Roll No: " << rollNo << endl;
        cout << "Student Name: " << name << endl;
    }
};

// Derived class from Student
class Mark : public Student {
protected:
    int marks1, marks2, marks3;
public:
    void getMarks(int m1, int m2, int m3) {
        marks1 = m1;
        marks2 = m2;
        marks3 = m3;
    }
    void displayMarks() {
        cout << "Marks: " << endl << marks1 << marks2 << marks3;
    }
};

// Derived class from Mark
class Percentage : public Mark {
public:
    void displayPercentage() {
        float total = marks1 + marks2 + marks3;
        float percentage = (total / 300) * 100;
        cout << "Total Marks: " << total << endl;
        cout << "Percentage: " << percentage << "%" << endl;
    }
};

int main() {
    Percentage stu;
    stu.getStudentDetails(101, "yyy");
    stu.getMarks(85, 90, 88);
    stu.displayStudentDetails();
    stu.displayMarks();
    stu.displayPercentage();
    return 0;
}
  • Execution Output:

    • Student Roll No: 101

    • Student Name: yyy

    • Marks:

    • 859088

    • Total Marks: 263

    • Percentage: 87.666

    • 3. Multiple Inheritance:

  • Definition: A paradigm where a single child class inherits directly from two or more distinct base classes simultaneously, combining independent feature sets into one entity.

  • Structural Diagram:

Multiple Inheritance Base Class 1 and Base Class 2 to Derived Class

  • Syntax:
    • Multiple parent classes are specified after the colon, separated by commas:
class Base1 {
    // Members of Base1
};
class Base2 {
    // Members of Base2
};
class Derived : public Base1, public Base2 {
    // Members of Derived
};
  • Code Implementation:
#include <iostream>
using namespace std;

class Shape {
protected:
    int width;
    int height;
public:
    void setval(int w, int h) {
        width = w;
        height = h;
    }
};

class shapearea {
public:
    int getCost(int area) {
        return area * 70;
    }
};

class Rectangle: public Shape, public shapearea {
public:
    int getArea() {
        return (width * height);
    }
};

int main(void) {
    Rectangle Rect;
    int area;
    Rect.setval(5, 7);
    area = Rect.getArea();
    cout << "Total area: " << Rect.getArea() << endl;
    cout << "Total cost: $" << Rect.getCost(area) << endl;
    return 0;
}
  • Execution Output:

    • Total area: 35

    • Total cost: $2450

    • 4. Hierarchical Inheritance:

  • Definition: A structure in which multiple specialized derived classes inherit directly from a common single base class.

  • Key Features:

    • Enables diverse subclasses to reuse common foundational logic while declaring divergent specialized capabilities.
    • Prevents horizontal code duplication across related classes.
    • Each derived class receives its own distinct copy of the accessible base class members.
  • Syntax:

class Base {
    // Base class members
};
class Derived1 : public Base {
    // Derived1 members
};
class Derived2 : public Base {
    // Derived2 members
};
  • Code Implementation:
#include <iostream>
using namespace std;

// Base class
class Person {
protected:
    string name;
    int age;
public:
    void getDetails(string n, int a) {
        name = n;
        age = a;
    }
    void displayDetails() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

// Derived class for Student
class Student : public Person {
private:
    int rollNo;
    int marks;
public:
    void getStudentDetails(int r, int m) {
        rollNo = r;
        marks = m;
    }
    void displayStudentDetails() {
        cout << "Student Details:" << endl;
        displayDetails();
        cout << "Roll No: " << rollNo << endl;
        cout << "Marks: " << marks << endl;
    }
};

// Derived class for Teacher
class Teacher : public Person {
private:
    int employeeID;
    string subject;
public:
    void getTeacherDetails(int id, string sub) {
        employeeID = id;
        subject = sub;
    }
    void displayTeacherDetails() {
        cout << "Teacher Details:" << endl;
        displayDetails();
        cout << "Employee ID: " << employeeID << endl;
        cout << "Subject: " << subject << endl;
    }
};

int main() {
    // Creating Student object
    Student student;
    student.getDetails("Alice", 20);
    student.getStudentDetails(101, 88);
    student.displayStudentDetails();
    cout << endl;

    // Creating Teacher object
    Teacher teacher;
    teacher.getDetails("Mr. Smith", 40);
    teacher.getTeacherDetails(2021, "Mathematics");
    teacher.displayTeacherDetails();
    return 0;
}
  • Execution Output:

    • Student Details:

    • Name: Alice

    • Age: 20

    • Roll No: 101

    • Marks: 88

    • Teacher Details:

    • Name: Mr. Smith

    • Age: 40

    • Employee ID: 2021

    • Subject: Mathematics

    • 5. Hybrid Inheritance:

  • Definition: A compound inheritance model that combines two or more different inheritance types (such as single, multiple, multilevel, and hierarchical) within a unified class hierarchy.

  • Core Characteristics:

    • Offers maximum design flexibility for enterprise-level or complex entity modeling.
    • Prone to severe architectural ambiguities, specifically the "Diamond Problem" when multiple paths lead back to a single root ancestor.
  • Structural Diagram:

Hybrid Inheritance Architecture Diagram

  • Code Implementation:
#include <iostream>
using namespace std;

// Base class
class Person {
protected:
    string name;
public:
    Person(const string& name) : name(name) {}
    void display() {
        cout << "
Name: " << name << endl;
    }
};

// Derived class 1: Employee (Single Inheritance)
class Employee : public Person {
protected:
    int employeeId;
public:
    Employee(const string& name, int id) : Person(name), employeeId(id) {}
    void displayEmployee() {
        display();
        cout << "Employee ID: " << employeeId << endl;
        cout << "Method inside Derived Class Employee" << endl;
    }
};

// Derived class 2: Student (Single Inheritance)
class Student : public Person {
protected:
    int studentId;
public:
    Student(const string& name, int id) : Person(name), studentId(id) {}
    void displayStudent() {
        display();
        cout << "Student ID: " << studentId << endl;
        cout << "Method inside Derived Class Student" << endl;
    }
};

// Derived class 3: StudentIntern (Multiple Inheritance)
class StudentIntern : public Employee, public Student {
public:
    StudentIntern(const string& name, int empId, int stuId)
        : Employee(name, empId), Student(name, stuId) {}
    void displayStudentIntern() {
        cout << "Methods inside Derived Class StudentIntern : " << endl;
        displayEmployee();
        displayStudent();
    }
};

int main() {
    StudentIntern SI("Riya", 67537, 2215);
    SI.displayStudentIntern();
    return 0;
}
  • Execution Output:
    • Methods inside Derived Class StudentIntern :
    • Name: Riya
    • Employee ID: 67537
    • Method inside Derived Class Employee
    • Name: Riya
    • Student ID: 2215
    • Method inside Derived Class Student

Constructor and Destructor Call Order in Inheritance

  • Fundamental Execution Lifecycle:

    • Constructor Invocation: Executes hierarchically from base to derived. When an instance of a derived class is allocated, the base class constructor executes first to construct the inherited foundations, followed by derived constructors.
    • Destructor Invocation: Executes strictly in reverse order from derived to base. When an object leaves scope or is dynamically freed, the derived class destructor cleans up local resources first, followed by the base class destructor.
    • Parameterized Base Constructors: If a base class constructor requires parameters, the derived class constructor must explicitly invoke it via an initialization list.
    • Virtual Destructors: Must be declared in polymorphic base classes to prevent undefined cleanup and memory leaks.
    • Multiple Inheritance Order: Constructors execute from left to right strictly following the order of declaration in the class header list, not the sequence written inside the constructor initialization list.
  • Sequence Diagram across Inheritance Types:

Constructor and Destructor Call Sequence Across Inheritance Types

  • Exhaustive Tracing Program:
#include <iostream>
using namespace std;

// ===== Base Classes =====
class A {
public:
    A() { cout << "Constructor A
"; }
    ~A() { cout << "Destructor A
"; }
};

class B {
public:
    B() { cout << "Constructor B
"; }
    ~B() { cout << "Destructor B
"; }
};

class C {
public:
    C() { cout << "Constructor C
"; }
    ~C() { cout << "Destructor C
"; }
};

// ===== 1. Single Inheritance =====
class SingleDerived : public A {
public:
    SingleDerived() { cout << "Constructor SingleDerived
"; }
    ~SingleDerived() { cout << "Destructor SingleDerived
"; }
};

// ===== 2. Multiple Inheritance =====
class MultipleDerived : public A, public B {
public:
    MultipleDerived() { cout << "Constructor MultipleDerived
"; }
    ~MultipleDerived() { cout << "Destructor MultipleDerived
"; }
};

// ===== 3. Multilevel Inheritance =====
class Level2 : public A {
public:
    Level2() { cout << "Constructor Level2
"; }
    ~Level2() { cout << "Destructor Level2
"; }
};

class Level3 : public Level2 {
public:
    Level3() { cout << "Constructor Level3
"; }
    ~Level3() { cout << "Destructor Level3
"; }
};

// ===== 4. Hierarchical Inheritance =====
class HierDerived1 : public A {
public:
    HierDerived1() { cout << "Constructor HierDerived1
"; }
    ~HierDerived1() { cout << "Destructor HierDerived1
"; }
};

class HierDerived2 : public A {
public:
    HierDerived2() { cout << "Constructor HierDerived2
"; }
    ~HierDerived2() { cout << "Destructor HierDerived2
"; }
};

// ===== 5. Hybrid Inheritance =====
class Hybrid : public A, public B {
public:
    Hybrid() { cout << "Constructor Hybrid
"; }
    ~Hybrid() { cout << "Destructor Hybrid
"; }
};

class HybridDerived : public Hybrid, public C {
public:
    HybridDerived() { cout << "Constructor HybridDerived
"; }
    ~HybridDerived() { cout << "Destructor HybridDerived
"; }
};

int main() {
    cout << "
--- Single Inheritance ---
";
    {
        SingleDerived obj;
    }
    cout << "
--- Multiple Inheritance ---
";
    {
        MultipleDerived obj;
    }
    cout << "
--- Multilevel Inheritance ---
";
    {
        Level3 obj;
    }
    cout << "
--- Hierarchical Inheritance ---
";
    {
        HierDerived1 obj1;
        HierDerived2 obj2;
    }
    cout << "
--- Hybrid Inheritance ---
";
    {
        HybridDerived obj;
    }
    return 0;
}
  • Execution Traces and Order Rules:
    • Single Inheritance:
    • Order: Constructor A →\rightarrow Constructor SingleDerived →\rightarrow Destructor SingleDerived →\rightarrow Destructor A
    • Rule: Base →\rightarrow Derived for construction; Derived →\rightarrow Base for destruction.
    • Multiple Inheritance:
    • Order: Constructor A →\rightarrow Constructor B →\rightarrow Constructor MultipleDerived →\rightarrow Destructor MultipleDerived →\rightarrow Destructor B →\rightarrow Destructor A
    • Rule: Base classes instantiate in left-to-right declaration order; destruction occurs in strict reverse.
    • Multilevel Inheritance:
    • Order: Constructor A →\rightarrow Constructor Level2 →\rightarrow Constructor Level3 →\rightarrow Destructor Level3 →\rightarrow Destructor Level2 →\rightarrow Destructor A
    • Rule: Top-most base →\rightarrow intermediate classes →\rightarrow most derived class; destruction unwinds in reverse.
    • Hierarchical Inheritance:
    • Order: Constructor A →\rightarrow Constructor HierDerived1 →\rightarrow Destructor HierDerived1 →\rightarrow Destructor A followed by Constructor A →\rightarrow Constructor HierDerived2 →\rightarrow Destructor HierDerived2 →\rightarrow Destructor A
    • Rule: Each independent derived object allocates and frees its own distinct base class instance.
    • Hybrid Inheritance:
    • Order: Constructor A →\rightarrow Constructor B →\rightarrow Constructor Hybrid →\rightarrow Constructor C →\rightarrow Constructor HybridDerived →\rightarrow Destructor HybridDerived →\rightarrow Destructor C →\rightarrow Destructor Hybrid →\rightarrow Destructor B →\rightarrow Destructor A
    • Rule: Multiple base classes build in declaration order before derived class construction; unwinding executes in exact mirror reverse.

Virtual Base Classes & The Diamond Problem

  • The Ambiguity Dilemma (The Diamond Problem):

    • Occurs when class A is inherited by two separate classes B and C, and both B and C are subsequently inherited by class D.
    • As a consequence, two duplicate instances of class A's fields and methods are injected into class D (one via path A →\rightarrow B →\rightarrow D and one via path A →\rightarrow C →\rightarrow D).
    • Any invocation of class A's members via an object of class D generates a fatal compiler ambiguity error because the compiler cannot determine which inherited instance to access.
  • Structural Diamond Diagram:

Diamond Problem Architecture Class A to B and C to D

  • Ambiguity Demonstration Code:
#include <iostream>
using namespace std;

class A {
public:
    void show() {
        cout << "Hello from A 
";
    }
};

class B : public A {};
class C : public A {};
class D : public B, public C {};

int main() {
    D object;
    object.show(); // Ambiguous call
}
  • Compiler Diagnostic Error:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
    object.show();
         ^
prog.cpp:8:8: note: candidates are: void A::show()
 void show()
      ^
prog.cpp:8:8: note: void A::show()
  • Virtual Base Class Solution:

    • By prepending the virtual keyword to the inheritance declaration of intermediate classes B and C, class A becomes a virtual base class.
    • Syntax Variants:
    • class B : virtual public A { };
    • class C : public virtual A { };
    • The keyword virtual may be positioned before or after public.
    • Mechanism: The compiler ensures that only one single, shared instance of class A is embedded within class D, eliminating ambiguity and redundant memory usage.
  • Resolved Code Implementation:

#include <iostream>
using namespace std;

class A {
public:
    int a;
    A() { // constructor
        a = 10;
    }
};

class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};

int main() {
    D object; // Single shared instance of A
    cout << "a = " << object.a << endl;
    return 0;
}
  • Output:
    • a = 10

Function Overloading

  • Concept and Mechanism:

    • Allows multiple functions within the same scope to share the same identifier while possessing distinct parameter signatures.
    • Overload resolution is decided strictly at compile time based upon:
    • Number of arguments passed.
    • Data types of arguments.
    • Sequence/order of argument types.
    • Return Type Restriction: Altering the return type alone does not constitute an overload; overloaded functions must have varying parameter lists.
  • Code Implementation:

#include <iostream>
using namespace std;

// Function to add two integers
int add(int a, int b) {
    return a + b;
}

// Function to add three integers
int add(int a, int b, int c) {
    return a + b + c;
}

// Overloading with different types
double add(double a, double b) {
    return a + b;
}

int main() {
    cout << add(1, 2) << endl;       // Calls 2-parameter int overload
    cout << add(1, 2, 3) << endl;    // Calls 3-parameter int overload
    cout << add(1.5, 2.5) << endl;   // Calls double overload
    return 0;
}
  • Benefits of Overloading:
    • Readability: Provides unified interfaces for identical semantic operations across disparate types.
    • Reusability: Avoids polluting namespaces with unique names (such as addInt, addDouble).
    • Polymorphism: Direct form of compile-time (static) polymorphism.

Operator Overloading

  • Foundational Rules:

    • Enables custom user-defined types (classes and structs) to redefine the semantics of C++ operators.
    • Only existing operators can be overloaded; entirely new operator symbols cannot be invented.
    • Overloaded operators may be implemented as non-static member functions or as external friend functions.
    • Syntax: return_type operator<symbol>(parameters)
  • Operators That Cannot Be Overloaded:

    • Size evaluation operator: sizeof
    • Run-time type identifier: typeid
    • Scope resolution operator: ::
    • Member access / selection operator: .
    • Pointer-to-member operator: .*
    • Ternary conditional operator: ?:
  • Complex Number Overloading Implementation:

#include <iostream>
#include <cmath>
using namespace std;

class Complex {
private:
    double real;
    double imag;
public:
    // Constructor with default values
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    // Overload the + operator
    Complex operator+(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }

    // Overload the << operator for formatted streaming
    friend ostream& operator<<(ostream& out, const Complex& c) {
        out << c.real << (c.imag >= 0 ? " + " : " - ") << abs(c.imag) << "i";
        return out;
    }
};

int main() {
    Complex c1(3.5, 2.5);
    Complex c2(1.5, -4.5);
    Complex sum = c1 + c2; // Uses overloaded +
    cout << "First Complex Number: " << c1 << endl;
    cout << "Second Complex Number: " << c2 << endl;
    cout << "Sum: " << sum << endl;
    return 0;
}
  • Execution Output:
    • First Complex Number: 3.5 + 2.5i
    • Second Complex Number: 1.5 - 4.5i
    • Sum: 5 + -2i

Compile-Time vs Runtime Polymorphism

  • Polymorphism Overview:

    • Derives from Greek meaning "many forms," enabling entities to respond differently to the same message based on operational context.
    • Categorized into two primary mechanics: Compile-Time (Early/Static) and Runtime (Late/Dynamic).
  • 1. Compile-Time Polymorphism:

    • Binding occurs during compilation based on static signatures.
    • Demonstrated via function overloading and operator overloading.
    • String Concatenation Overload Example:
#include <iostream>
#include <string>
using namespace std;

class StringConcat {
private:
    string str;
public:
    StringConcat() : str("") {}
    StringConcat(string s) : str(s) {}

    StringConcat operator+(const StringConcat& obj) {
        StringConcat result;
        result.str = this->str + obj.str;
        return result;
    }
    void display() {
        cout << "Concatenated String: " << str << endl;
    }
};

int main() {
    StringConcat str1("Hello");
    StringConcat str2("World");
    StringConcat result = str1 + str2;
    result.display();
    return 0;
}
  • Output: Concatenated String: HelloWorld

    • 2. Runtime Polymorphism:
  • Resolved dynamically during program execution using function overriding and base pointers.

  • Requires class inheritance and the virtual keyword declared on base class methods.

  • Function Overriding Example:

#include <iostream>
using namespace std;

class Car {
public:
    virtual void displayColor() {
        cout << "The car is colored in default color." << endl;
    }
    virtual void displayBrand() {
        cout << "This is a generic car." << endl;
    }
};

class RedCar : public Car {
public:
    void displayColor() override {
        cout << "The car is colored red." << endl;
    }
};

class BlueCar : public Car {
public:
    void displayColor() override {
        cout << "The car is colored blue." << endl;
    }
};

int main() {
    Car* car1 = new RedCar();
    Car* car2 = new BlueCar();
    car1->displayColor();
    car2->displayColor();
    delete car1;
    delete car2;
    return 0;
}
  • Output:

    • The car is colored red.

    • The car is colored blue.

    • Comprehensive Comparison Table:

FeatureCompile-Time PolymorphismRuntime Polymorphism
DefinitionDetermines target function based on argument count, type, and order during compilation.Determines target function at runtime based on the actual concrete type of the object pointed to.
Binding MechanismStatic binding / Early binding.Dynamic binding / Late binding.
Alternate NamesStatic polymorphism.Dynamic polymorphism.
Function OverloadingCore implementation path.Not applicable.
Operator OverloadingCore implementation path.Not applicable.
Inheritance RequirementNot required.Mandates inheritance and base pointer/reference usage.
Execution SpeedFaster, as all address resolutions complete ahead of execution.Comparatively slower due to pointer indirection overhead via vTables.
Code ReusabilityAchieved by mapping varied parameter sets to standard routines.Achieved by invoking specialized derived behaviors via a uniform base interface.
Implementation MethodsFunction overloading and operator overloading.Virtual functions and function overriding.

Pure Virtual Functions & Abstract Classes

  • Pure Virtual Functions:

    • A virtual function declared in a base class with no implementation provided, designated by appending = 0 to its prototype.
    • Syntax: virtual <return_type> <func_name>(<params>) = 0;
    • Serves as an interface contract that mandates derived classes to supply concrete implementations.
    • Cannot be static or declared as global functions.
  • Abstract Classes:

    • Any class possessing at least one pure virtual function automatically becomes an abstract class.
    • Direct Instantiation Prohibited: Cannot create direct instances (e.g., Shape s; yields compilation failure).
    • Base class pointers and references of the abstract type are completely valid and support polymorphic routing.
    • Derived classes must override every pure virtual function; failing to do so renders the derived class abstract as well.
  • Comparative Distinctions:

FeatureVirtual FunctionPure Virtual Function
ImplementationFull definition provided in base class.No definition provided in base class (= 0).
InstantiationBase class can be instantiated directly.Base class becomes abstract and cannot be instantiated.
Overriding RequirementOptional in derived classes.Mandatory in derived classes to become concrete.
Syntaxvirtual void display() { ... }virtual void display() = 0;
Non-overridden EffectDerived inherits base behavior without compilation issue.Derived becomes abstract; object instantiation fails.
  • Complete Abstract Architecture Program:
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

// Abstract base class
class Shape {
public:
    // Pure virtual functions
    virtual double area() const = 0;
    virtual double perimeter() const = 0;

    // Non-pure virtual function
    virtual void display() const {
        cout << "This is a shape." << endl;
    }

    // Virtual destructor for safe polymorphic deletion
    virtual ~Shape() {}
};

// Derived concrete class: Circle
class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {
        if (r <= 0) throw invalid_argument("Radius must be positive.");
    }
    double area() const override {
        return 3.14159 * radius * radius;
    }
    double perimeter() const override {
        return 2 * 3.14159 * radius;
    }
    void display() const override {
        cout << "Circle with radius " << radius << endl;
    }
};

// Derived concrete class: Rectangle
class Rectangle : public Shape {
private:
    double length, width;
public:
    Rectangle(double l, double w) : length(l), width(w) {
        if (l <= 0 || w <= 0) throw invalid_argument("Length and width must be positive.");
    }
    double area() const override {
        return length * width;
    }
    double perimeter() const override {
        return 2 * (length + width);
    }
    void display() const override {
        cout << "Rectangle " << length << " x " << width << endl;
    }
};

int main() {
    try {
        Shape* shapes[2];
        shapes[0] = new Circle(5);
        shapes[1] = new Rectangle(4, 6);

        for (Shape* s : shapes) {
            s->display();
            cout << "Area: " << s->area() << endl;
            cout << "Perimeter: " << s->perimeter() << endl << endl;
            delete s; // Virtual destructor ensures proper cleanup
        }
    } catch (const exception& e) {
        cerr << "Error: " << e.what() << endl;
    }
    return 0;
}
  • Execution Output:
    • Circle with radius 5
    • Area: 78.5397
    • Perimeter: 31.4159
    • Rectangle 4 x 6
    • Area: 24
    • Perimeter: 20

Virtual Destructors

  • Purpose and Critical Requirement:

    • When deleting a dynamically allocated derived class instance via a pointer to its base class (Base* ptr = new Derived(); delete ptr;), a non-virtual destructor triggers undefined behavior.
    • Without a virtual destructor, the compiler performs static binding and calls only the base class destructor, leaving derived class resources orphaned in memory (memory leaks).
    • Declaring the base destructor virtual forces dynamic binding: the derived destructor is invoked first, cleanly freeing specialized allocations, before the base destructor executes.
    • Syntax: virtual ~Base() { }
  • Demonstration of Correct Virtual Destructor Cleanup:

#include <iostream>
using namespace std;

class Base {
public:
    Base() { cout << "Base Constructor
"; }
    virtual ~Base() { cout << "Base Destructor
"; }
};

class Derived : public Base {
public:
    Derived() { cout << "Derived Constructor
"; }
    ~Derived() override { cout << "Derived Destructor
"; }
};

int main() {
    Base *basePtr = new Derived();
    delete basePtr;
    return 0;
}
  • Execution Output:
    • Base Constructor
    • Derived Constructor
    • Derived Destructor
    • Base Destructor

Virtual Table (vTable) and Virtual Pointer (vPtr) Mechanics

  • The Dynamic Dispatch Architecture:

    • vTable (Virtual Function Table): A static lookup table created by the compiler for every polymorphic class (any class defining or inheriting at least one virtual function or virtual destructor). It stores function pointers to the actual virtual member function implementations associated with that specific class.
    • vPtr (Virtual Pointer): An implicit hidden pointer added to the memory footprint of every object instance of a polymorphic class. It initializes during constructor execution to point directly to the corresponding class vTable.
  • Memory Representation Diagram:

Memory Representation of vPtr and Vtable across Classes A, B, and C

  • Low-Level Code Implementation Tracing vTables:
#include <iostream>
using namespace std;

class A {
public:
    virtual void f1() { cout << "A::f1 called" << endl; }
    virtual void f2() { cout << "A::f2 called" << endl; }
    virtual ~A() { cout << "Class A destructor called" << endl; }
};

class B : public A {
public:
    void f1() override { cout << "B::f1 called" << endl; }
    void f2() override { cout << "B::f2 called" << endl; }
    ~B() override { cout << "Class B destructor called" << endl; }
};

class C : public A {
public:
    void f1() override { cout << "C::f1 called" << endl; }
    void f2() override { cout << "C::f2 called" << endl; }
    ~C() override { cout << "Class C destructor called" << endl; }
};

int main() {
    A* ptrB = new B();
    A* ptrC = new C();

    cout << "Calling functions using pointer B:" << endl;
    ptrB->f1();
    ptrB->f2();

    cout << "Calling functions using pointer C:" << endl;
    ptrC->f1();
    ptrC->f2();

    // Calling B's destructor then A's destructor
    delete ptrB;
    // Calling C's destructor then A's destructor
    delete ptrC;
    return 0;
}
  • Execution Output:

    • Calling functions using pointer B:

    • B::f1 called

    • B::f2 called

    • Calling functions using pointer C:

    • C::f1 called

    • C::f2 called

    • Class B destructor called

    • Class A destructor called

    • Class C destructor called

    • Class A destructor called

    • Architectural Comparison: VPTR vs VTable:

CharacteristicVPTR (Virtual Pointer)VTable (Virtual Function Table)
Entity TypeImplicit per-object pointer variable.Per-class static array of function pointers.
AllocationResides inside every instantiated object's layout.Allocated once per class in read-only program memory.
Reference TargetPoints directly to the class's VTable.Points to virtual member functions and destructors.
Primary RoleProvides object-to-table runtime link.Resolves function addresses for dispatch.
  • Engineering Trade-offs:
    • Advantages: Unlocks pure runtime polymorphism, enables loose coupling, facilitates extensibility in framework designs, and empowers complex software systems (e.g., game engines, GUI libraries, simulation platforms).
    • Disadvantages:
    • Memory Overhead: Adds hidden storage cost per object (44 or 88 bytes for vptr) plus class-level tables.
    • Call Latency Overhead: Dispatches through an extra layer of pointer indirection, inhibiting compiler inline optimizations.
    • Layout Complexity: Increases binary and object layout complexity.

Run-Time Type Information (RTTI)

  • Conceptual Overview:
    • RTTI allows a program to interrogate and discover the concrete runtime data type of an object referenced by a polymorphic base pointer or reference.
    • Requires that the base class contains at least one virtual function to enable runtime type resolution.
    • Architectural Components:

RTTI Component Architecture

  • 1. dynamic_cast Operator:
    • Safely converts a pointer or reference of a base class to a derived class within an inheritance hierarchy (downcasting).
    • Validation Rule: If downcasting a pointer fails (the underlying object is not the target derived type), it returns nullptr. If downcasting a reference fails, it throws a std::bad_cast exception.
    • Syntax: dynamic_cast<target_type>(expression);
    • Code Implementation:
#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() {
        cout << "Animal Sound" << endl;
    }
    virtual ~Animal() {}
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Dog Barks" << endl;
    }
};

int main() {
    Animal *ptr = new Dog();
    Dog *d = dynamic_cast<Dog*>(ptr);
    if (d != nullptr) {
        d->bark();
    }
    delete ptr;
    return 0;
}
  • Output: Dog Barks

    • 2. typeid Operator and type_info Class:
  • Syntax: typeid(expression) or typeid(type)

  • Included via standard header: #include <typeinfo>

  • Returns a reference to an immutable standard type_info object (const type_info&).

  • .name() Method: Yields an implementation-dependent, compiler-mangled C-string representing the type name.

  • Comparison Operators (== and !=): Directly compares runtime type equality between objects or expressions:

if (typeid(*ptr) == typeid(Dog)) {
    cout << "Object is Dog";
}
if (typeid(*ptr) != typeid(Cat)) {
    cout << "Object is not Cat";
}
  • Enterprise Application: Polymorphic Payment Gateway:
#include <iostream>
using namespace std;

class Payment {
public:
    virtual void pay() {
        cout << "Payment";
    }
    virtual ~Payment() {}
};

class CreditCard : public Payment {
public:
    void pay() override {
        cout << "Credit Card Payment";
    }
    void cardDetails() {
        cout << "Card details";
    }
};

int main() {
    Payment *p = new CreditCard();
    CreditCard *c = dynamic_cast<CreditCard*>(p);
    if (c != nullptr) {
        c->cardDetails();
    }
    delete p;
    return 0;
}
  • Output: Card details

    • Trade-Offs of RTTI:
  • Advantages: Guarantees runtime safety against invalid casts, provides debugging/logging type inspection, and supports heterogeneous object collections.

  • Disadvantages: Introduces runtime execution cost; adds storage overhead; overuse often flags design flaws indicating poor polymorphic architecture where standard virtual dispatch should have been leveraged.

Practical Implementations: Array and Time Operations

  • 1. Array Management via Inheritance:
    • Inherits core data storage to perform aggregate calculations across multiple values.
#include <iostream>
using namespace std;

// Base class
class Student {
protected:
    int marks[5];
public:
    void getMarks() {
        cout << "Enter marks for 5 subjects: ";
        for (int i = 0; i < 5; i++) {
            cin >> marks[i];
        }
    }
};

// Derived class
class Result : public Student {
public:
    void displayResult() {
        int total = 0;
        float average;
        for (int i = 0; i < 5; i++) {
            total = total + marks[i];
        }
        average = total / 5.0;
        cout << "
Total Marks = " << total;
        cout << "
Average Marks = " << average;
    }
};

int main() {
    Result r;
    r.getMarks();
    r.displayResult();
    return 0;
}
  • 2. Vectorized Array Addition (+ Operator Overload):
    • Implements element-wise parallel array summation across two encapsulated instances.
#include <iostream>
using namespace std;

class Array {
    int a[5];
public:
    void getData() {
        cout << "Enter 5 elements: ";
        for (int i = 0; i < 5; i++) cin >> a[i];
    }
    void display() {
        for (int i = 0; i < 5; i++) cout << a[i] << " ";
        cout << endl;
    }
    Array operator+(Array obj) {
        Array temp;
        for (int i = 0; i < 5; i++) {
            temp.a[i] = a[i] + obj.a[i];
        }
        return temp;
    }
};

int main() {
    Array A, B, C;
    cout << "Enter first array:
";
    A.getData();
    cout << "Enter second array:
";
    B.getData();
    C = A + B;
    cout << "First array: ";
    A.display();
    cout << "Second array: ";
    B.display();
    cout << "Sum of arrays: ";
    C.display();
    return 0;
}
  • 3. Element-wise Array Multiplication (* Operator Overload):
    • Multiplies matching indices of two separate array objects.
#include <iostream>
using namespace std;

class Array {
    int a[5];
public:
    void getData() {
        cout << "Enter 5 elements: ";
        for (int i = 0; i < 5; i++) cin >> a[i];
    }
    void display() {
        for (int i = 0; i < 5; i++) cout << a[i] << " ";
        cout << endl;
    }
    Array operator*(Array obj) {
        Array temp;
        for (int i = 0; i < 5; i++) {
            temp.a[i] = a[i] * obj.a[i];
        }
        return temp;
    }
};

int main() {
    Array A, B, C;
    cout << "Enter first array:
";
    A.getData();
    cout << "Enter second array:
";
    B.getData();
    C = A * B;
    cout << "Product of arrays: ";
    C.display();
    return 0;
}
  • 4. Array Sum Comparison (> Operator Overload):
    • Evaluates aggregate summation to decide magnitude precedence between two objects.
#include <iostream>
using namespace std;

class Array {
    int a[5];
public:
    void getData() {
        cout << "Enter 5 elements: ";
        for (int i = 0; i < 5; i++) cin >> a[i];
    }
    int sum() {
        int total = 0;
        for (int i = 0; i < 5; i++) total += a[i];
        return total;
    }
    bool operator>(Array obj) {
        return sum() > obj.sum();
    }
};

int main() {
    Array A, B;
    cout << "Enter first array:
";
    A.getData();
    cout << "Enter second array:
";
    B.getData();
    cout << "Sum of first array = " << A.sum() << endl;
    cout << "Sum of second array = " << B.sum() << endl;
    if (A > B)
        cout << "First array has the larger sum.";
    else if (B > A)
        cout << "Second array has the larger sum.";
    else
        cout << "Both arrays have equal sums.";
    return 0;
}
  • 5. Array Equality Comparison (== Operator Overload):
    • Checks identical element-by-element equality across array bounds.
#include <iostream>
using namespace std;

class Array {
    int a[5];
public:
    void getData() {
        cout << "Enter 5 elements: ";
        for (int i = 0; i < 5; i++) cin >> a[i];
    }
    bool operator==(Array obj) {
        for (int i = 0; i < 5; i++) {
            if (a[i] != obj.a[i])
                return false;
        }
        return true;
    }
};

int main() {
    Array A, B;
    cout << "Enter first array:
";
    A.getData();
    cout << "Enter second array:
";
    B.getData();
    if (A == B)
        cout << "Both arrays are equal.";
    else
        cout << "Arrays are not equal.";
    return 0;
}
  • 6. Custom Time Addition with Base-60 Normalization (+ Operator Overload):
    • Normalizes minutes and hours when minutes exceed 6060.
#include <iostream>
using namespace std;

class Time {
    int hours, minutes;
public:
    void getData() {
        cout << "Enter hours and minutes: ";
        cin >> hours >> minutes;
    }
    void display() {
        cout << hours << " hours " << minutes << " minutes";
    }
    Time operator+(Time t) {
        Time temp;
        temp.minutes = minutes + t.minutes;
        temp.hours = hours + t.hours;
        if (temp.minutes >= 60) {
            temp.hours += temp.minutes / 60;
            temp.minutes = temp.minutes % 60;
        }
        return temp;
    }
};

int main() {
    Time T1, T2, T3;
    cout << "Enter first time:
";
    T1.getData();
    cout << "Enter second time:
";
    T2.getData();
    T3 = T1 + T2;
    cout << "
First time: ";
    T1.display();
    cout << "
Second time: ";
    T2.display();
    cout << "
Total time: ";
    T3.display();
    return 0;
}