Comprehensive Study Notes on C++ Inheritance, Polymorphism, and Runtime Mechanics

Unit Overview: Inheritance and Polymorphism in C++

  • Course and Subject Context: Code/Subject: AD/AM/IT/CB/CZ/CS6101– OBJECT ORIENTED PROGRAMMING USING C++.

  • Unit Classification: UNIT-II: INHERITANCE AND POLYMORPHISM.

  • Scope of Coverage:

    • Types of Inheritance: Single, Multiple, Multilevel, Hierarchical, Hybrid.

    • Order of Constructor and Destructor calls.

    • Virtual base classes and diamond hierarchy resolution.

    • Compile-Time Polymorphism: Function Overloading and Operator Overloading.

    • Runtime Polymorphism: Virtual Functions, Function Overriding, Pure Virtual Functions, and Abstract Classes.

    • Safe resource cleanup via Virtual Destructors.

    • Internal mechanics: Virtual Tables (vTable\text{vTable}) and Virtual Pointers (vPtr\text{vPtr}).

    • Run-Time Type Information (RTTI\text{RTTI}): Runtime type verification via dynamic_cast and identification via typeid.

  • Core OOP Design Principles:

    • Subtype Modeling: Prefer inheritance for genuine subtype relationships ("is-a").

    • Composition Alternative: Consider composition when one class merely needs to utilize another class's functionality without representing an identity relationship.

    • Data Member Roles: Base-class data members store shared attributes across related classes, while derived-class data members store specialized attributes.

    • Interface Preservation: Public inheritance preserves the base class's public interface and represents strict subtyping.

Single Inheritance

  • Formal Definition: Single inheritance occurs when one derived class inherits directly from exactly one base class. It is also known as simple inheritance, wherein the derived class inherits the properties and member functions of a single base class.

  • Structural Relationship:

    • A single derived class specializes a single general class.      

      Single inheritance hierarchy showing Base Class Person and Derived Class Student
  • General Syntax:

  class Base {
      // Data members and member functions
  };

  class Derived : access_specifier Base {
      // Additional data members and member functions
  };
  ```
- **Complete Program Implementation:**

cpp #include #include using namespace std;

class Person { public: string name; int age;

  void displayPerson() {
      cout << "Name: " << name << endl;
      cout << "Age: " << age << endl;
  }

};

class Student : public Person { public: int rollNo; string department;

  void displayStudent() {
      cout << "Roll Number: " << rollNo << endl;
      cout << "Department: " << department << endl;
  }

};

int main() { Student s; s.name = "Arun"; s.age = 18; s.rollNo = 101; s.department = "CSE";

  cout << "--- Person Details ---" << endl;
  s.displayPerson();

  cout << "--- Student Details ---" << endl;
  s.displayStudent();

  return 0;

}   ```

  • Execution Output:

  --- Person Details ---
  Name: Arun
  Age: 18
  --- Student Details ---
  Roll Number: 101
  Department: CSE
&nbsp;&nbsp;```
- **Step-by-Step Program Analysis:**
  - `string name; int age;`: Declares the base-class data members common to any person.
  - `displayPerson()`: Displays the common personal details stored in the base-class scope.
  - `class Student : public Person`: Defines public inheritance, making `Student` inherit all public members of `Person`.
  - `int rollNo; string department;`: Adds specialized student attributes.
  - `Student s;`: Instantiates a derived-class object containing memory layouts for both base and derived attributes.
  - `s.name = "Arun";`: Assigns value to the inherited base-class member `name`.
  - `s.age = 18;`: Assigns numerical value `1818` to the inherited base-class member `age`.
  - `s.rollNo = 101;`: Assigns numerical value `101101` to the derived-class member `rollNo`.
  - `s.displayPerson();`: Executes the inherited member function from `Person`.
  - `s.displayStudent();`: Executes the derived-class function declared within `Student`.
- **Real-Time Applications:**
  - **College Management Systems:** `Person` encapsulates `name` and `age`; `Student` extends with `rollNo`, `department`, and `semester`.
  - **Employee Management Systems:** `Person` maintains personal details; `Employee` appends `employeeId`, `salary`, and `designation`.
  - **Hospital Management Systems:** `Person` records common bio-data; `Doctor` extends with `specialization` and `registrationNumber`.
- **Applicability Condition:** Use single inheritance when a derived class is strictly an specialized form of one base class.

# Multiple Inheritance

- **Formal Definition:** Multiple inheritance occurs when a single derived class inherits properties, state, and member functions from two or more base classes simultaneously.
- **Structural Relationship:**
  - Combines orthogonal or distinct capabilities from separate classes into a consolidated type.
&nbsp;&nbsp;
&nbsp;&nbsp;![Multiple inheritance structure showing Academic and Sports base classes inheriting into Student](https://assets.knowt.com/pdf-flow-prod/87bc7ad5-6c32-4e53-8acd-df96a2abaae0-figures/1.png)

- **General Syntax:**

cpp class Base1 { // Data members and member functions };

class Base2 { // Data members and member functions };

class Derived : public Base1, public Base2 { // Additional data members and member functions };   ```

  • Complete Program Implementation:

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

  class Academic {
  public:
      int marks;

      void displayAcademic() {
          cout << "Academic Marks: " << marks << endl;
      }
  };

  class Sports {
  public:
      int sportsScore;

      void displaySports() {
          cout << "Sports Score: " << sportsScore << endl;
      }
  };

  class Student : public Academic, public Sports {
  public:
      string name;
      int rollNo;

      void displayStudent() {
          cout << "Name: " << name << endl;
          cout << "Roll Number: " << rollNo << endl;
      }
  };

  int main() {
      Student s;
      s.name = "Priya";
      s.rollNo = 102;
      s.marks = 450;
      s.sportsScore = 90;

      cout << "--- Student Details ---" << endl;
      s.displayStudent();

      cout << "--- Academic Details ---" << endl;
      s.displayAcademic();

      cout << "--- Sports Details ---" << endl;
      s.displaySports();

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text --- Student Details --- Name: Priya Roll Number: 102 --- Academic Details --- Academic Marks: 450 --- Sports Details --- Sports Score: 90   ```

  • Step-by-Step Program Analysis:

    • int marks;: Member in Academic storing academic marks (450450).

    • int sportsScore;: Member in Sports storing athletic points (9090).

    • class Student : public Academic, public Sports: Multiple base inheritance syntax, declaring that Student derives publicly from both parents.

    • string name; int rollNo;: Introduces student identity data members (name="Priya"\text{name} = \text{"Priya"}, rollNo=102\text{rollNo} = 102).

    • s.marks = 450; and s.sportsScore = 90;: Directly initializes inherited members from distinct base branches.

    • Member Reusability: A single object s encapsulates the memory and interfaces of both parent classes without re-declaring their member variables.

  • Name Ambiguity Resolution Rule:

    • If two base classes contain identical member identifiers (e.g., both define display()), invoking s.display() produces a compile-time ambiguity error.

    • Resolution Mechanism: Must use explicit scope resolution qualification (e.g., s.Academic::display()) or define an overriding function inside the derived class that disambiguates the call.

  • Real-Time Applications:

    • College Performance Systems: Aggregates coursework marks, attendance matrices, and sports participation metrics.

    • Smart Devices: An IoT device inheriting separate WiFiInterface and BluetoothInterface capabilities.

    • Office Automation: Multifunction printer systems deriving from both Printer and Scanner functional abstractions.

  • Applicability Condition: Use multiple inheritance when a class genuinely needs to combine distinct, independent features from multiple disparate types.

Multilevel Inheritance

  • Formal Definition: Multilevel inheritance occurs when a derived class is formed by inheriting from an existing derived class, creating an inheritance chain of successive parent-child generations.

  • Structural Relationship:

    • Models progressive specialization down an inheritance chain.      

      Multilevel inheritance chain diagram showing LivingThing to Animal to Dog
  • General Syntax:

  class A {
      // Base class
  };

  class B : public A {
      // Intermediate derived class B inherits from A
  };

  class C : public B {
      // Most-derived class C inherits from B
  };
&nbsp;&nbsp;```
- **Complete Program Implementation:**

cpp #include #include using namespace std;

class LivingThing { public: string species;

  void displayLivingThing() {
      cout << "Species: " << species << endl;
  }

};

class Animal : public LivingThing { public: string habitat;

  void displayAnimal() {
      cout << "Habitat: " << habitat << endl;
  }

};

class Dog : public Animal { public: string breed;

  void displayDog() {
      cout << "Breed: " << breed << endl;
  }

};

int main() { Dog d; d.species = "Dog"; d.habitat = "Domestic"; d.breed = "Labrador";

  cout << "--- Living Thing Details ---" << endl;
  d.displayLivingThing();

  cout << "--- Animal Details ---" << endl;
  d.displayAnimal();

  cout << "--- Dog Details ---" << endl;
  d.displayDog();

  return 0;

}   ```

  • Execution Output:

  --- Living Thing Details ---
  Species: Dog
  --- Animal Details ---
  Habitat: Domestic
  --- Dog Details ---
  Breed: Labrador
&nbsp;&nbsp;```
- **Step-by-Step Program Analysis:**
  - `string species;`: Top-level attribute in base class `LivingThing`.
  - `class Animal : public LivingThing`: First derivation level; adds `string habitat;`.
  - `class Dog : public Animal`: Second derivation level; inherits `Animal` (which transitively holds `LivingThing` members) and introduces `string breed;`.
  - `Dog d;`: Allocates storage for `species`, `habitat`, and `breed`.
  - Field Assignments: `d.species = "Dog";`, `d.habitat = "Domestic";`, `d.breed = "Labrador";`.
  - Execution calls traverse up the hierarchy: `d.displayLivingThing()`, `d.displayAnimal()`, and `d.displayDog()`.
- **Real-Time Applications:**
  - **Automotive Systems:** `Vehicle` →\rightarrow `Car` →\rightarrow `ElectricCar` (general vehicular kinematics →\rightarrow automobile mechanics →\rightarrow electric-powertrain telematics).
  - **Banking Software:** `Account` →\rightarrow `SavingsAccount` →\rightarrow `PremiumSavingsAccount` (adding progressively specialized tier features and interest brackets).
  - **Cybersecurity Architecture:** `SecurityEvent` →\rightarrow `NetworkEvent` →\rightarrow `SuspiciousNetworkEvent`.
- **Applicability Condition & Design Warning:** Use when a concept undergoes stepwise, natural domain specialization. Avoid excessively deep hierarchies, as excessive layering increases cognitive load and hampers long-term maintainability.

# Hierarchical Inheritance

- **Formal Definition:** Hierarchical inheritance occurs when multiple derived classes inherit from a single common base class.
- **Structural Relationship:**
  - Distributes common properties from a single parent across multiple peer child classes.
&nbsp;&nbsp;
&nbsp;&nbsp;![Hierarchical inheritance diagram displaying Shape as the common base class for Circle and Rectangle](https://assets.knowt.com/pdf-flow-prod/87bc7ad5-6c32-4e53-8acd-df96a2abaae0-figures/3.png)

- **General Syntax:**

cpp class A { // Base class };

class B : public A { // Derived class 1 };

class C : public A { // Derived class 2 };   ```

  • Complete Program Implementation:

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

  class Shape {
  public:
      string color;

      void displayColor() {
          cout << "Color: " << color << endl;
      }
  };

  class Circle : public Shape {
  public:
      double radius;

      void displayCircle() {
          cout << "Radius: " << radius << endl;
      }
  };

  class Rectangle : public Shape {
  public:
      double length;
      double width;

      void displayRectangle() {
          cout << "Length: " << length << endl;
          cout << "Width: " << width << endl;
      }
  };

  int main() {
      Circle c;
      Rectangle r;

      c.color = "Red";
      c.radius = 5.0;

      r.color = "Blue";
      r.length = 10.0;
      r.width = 4.0;

      cout << "--- Circle Details ---" << endl;
      c.displayColor();
      c.displayCircle();

      cout << "--- Rectangle Details ---" << endl;
      r.displayColor();
      r.displayRectangle();

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text --- Circle Details --- Color: Red Radius: 5 --- Rectangle Details --- Color: Blue Length: 10 Width: 4   ```

  • Step-by-Step Program Analysis:

    • string color;: Universal geometric property encapsulated in Shape.

    • class Circle : public Shape: Child class specialized with double radius; (5.05.0).

    • class Rectangle : public Shape: Child class specialized with double length; (10.010.0) and double width; (4.04.0).

    • Instantiations: Separate instances Circle c; and Rectangle r; are created on the stack.

    • Both classes reuse the shared data member color and function displayColor(), while isolating shape-specific dimensions to their respective classes.

  • Real-Time Applications:

    • CAD & Vector Graphics: Shape serves as the base; Circle, Rectangle, and Triangle add specialized geometry and rasterization.

    • University Directory Systems: Person provides base biological attributes; Student, Faculty, and Administrator add role-specific privileges.

    • Fleet & Transport Logistics: Vehicle holds VIN and registration; Car, Bus, and Motorcycle extend with seating capacity, axles, or engine classes.

  • Applicability Condition: Use when multiple sub-types share identical core characteristics but diverge in functional specialization.

Hybrid Inheritance and The Diamond Problem

  • Formal Definition: Hybrid inheritance is a structural pattern that integrates two or more distinct inheritance types (e.g., combining hierarchical and multiple inheritance). The canonical manifestation is the "Diamond Hierarchy".

  • Structural Relationship:

    • Base class A\text{A} is inherited by derived classes B\text{B} and C\text{C}, which in turn are both inherited by derived class D\text{D}.      

      Hybrid inheritance diamond diagram showing Person inherited by Student and Employee, uniting in TeachingAssistant
  • General Syntax:

  class A {
      // Base class
  };

  class B : public A {
      // Derived class B inherits A
  };

  class C : public A {
      // Derived class C inherits A
  };

  class D : public B, public C {
      // Derived class D inherits B and C
  };
&nbsp;&nbsp;```
- **Root Cause of the Diamond Problem:**
  - When class `Student` and class `Employee` both inherit from `Person`, each intermediate class retains an internal copy of `Person`.
  - When `TeachingAssistant` inherits from both `Student` and `Employee`, it receives two duplicate `Person` subobjects.
  - Consequently, referencing `ta.name` or `ta.age` directly causes a compiler error due to ambiguity: the compiler cannot discern which parent's `Person` subobject to access.

## Program Implementation Without Virtual Inheritance

- **C++ Source Code:**

cpp #include #include using namespace std;

class Person { public: string name; int age;

  Person() {
      name = "Unknown";
      age = 0;
  }

  void displayPerson() {
      cout << "Name: " << name << endl;
      cout << "Age: " << age << endl;
  }

};

class Student : public Person { public: int rollNo;

  void displayStudent() {
      cout << "--- Student Details ---" << endl;
      displayPerson();
      cout << "Roll Number: " << rollNo << endl;
  }

};

class Employee : public Person { public: int employeeId;

  void displayEmployee() {
      cout << "--- Employee Details ---" << endl;
      displayPerson();
      cout << "Employee ID: " << employeeId << endl;
  }

};

class TeachingAssistant : public Student, public Employee { public: string subject; double stipend;

  void displayTeachingAssistant() {
      cout << "--- Teaching Assistant Details ---" << endl;
      cout << "Subject: " << subject << endl;
      cout << "Stipend: " << stipend << endl;
  }

};

int main() { TeachingAssistant ta; ta.Student::name = "Kavin"; ta.Student::age = 21; ta.rollNo = 201;

  ta.Employee::name = "Kavin";
  ta.Employee::age = 21;
  ta.employeeId = 501;

  ta.subject = "C++";
  ta.stipend = 10000.0;

  ta.displayStudent();
  cout << endl;
  ta.displayEmployee();
  cout << endl;
  ta.displayTeachingAssistant();

  return 0;

}   ```

  • Execution Output:

  --- Student Details ---
  Name: Kavin
  Age: 21
  Roll Number: 201

  --- Employee Details ---
  Name: Kavin
  Age: 21
  Employee ID: 501

  --- Teaching Assistant Details ---
  Subject: C++
  Stipend: 10000
&nbsp;&nbsp;```
- **Mechanical Behavior:**
  - In the absence of virtual inheritance, accessing `ta.name` directly triggers a compilation error.
  - Access requires disambiguation using scope resolution: `ta.Student::name` and `ta.Employee::name`.
  - This duplicates state in memory, maintaining two separate names and ages for a single entity.

## Program Implementation With Virtual Inheritance (Resolving Diamond Ambiguity)

- **C++ Source Code:**

cpp #include #include using namespace std;

class Person { public: string name; int age;

  Person() {
      name = "Unknown";
      age = 0;
  }

  void displayPerson() {
      cout << "Name: " << name << endl;
      cout << "Age: " << age << endl;
  }

};

class Student : virtual public Person { public: int rollNo;

  void displayStudent() {
      cout << "--- Student Details ---" << endl;
      displayPerson();
      cout << "Roll Number: " << rollNo << endl;
  }

};

class Employee : virtual public Person { public: int employeeId;

  void displayEmployee() {
      cout << "--- Employee Details ---" << endl;
      displayPerson();
      cout << "Employee ID: " << employeeId << endl;
  }

};

class TeachingAssistant : public Student, public Employee { public: string subject; double stipend;

  void displayTeachingAssistant() {
      cout << "--- Teaching Assistant Details ---" << endl;
      cout << "Subject: " << subject << endl;
      cout << "Stipend: " << stipend << endl;
  }

};

int main() { TeachingAssistant ta; ta.name = "Kavin"; ta.age = 21; ta.rollNo = 201; ta.employeeId = 501; ta.subject = "C++"; ta.stipend = 10000.0;

  ta.displayStudent();
  cout << endl;
  ta.displayEmployee();
  cout << endl;
  ta.displayTeachingAssistant();

  return 0;

}   ```

  • Execution Output:

  --- Student Details ---
  Name: Kavin
  Age: 21
  Roll Number: 201

  --- Employee Details ---
  Name: Kavin
  Age: 21
  Employee ID: 501

  --- Teaching Assistant Details ---
  Subject: C++
  Stipend: 10000
&nbsp;&nbsp;```
- **Program Analysis and Mechanics:**
  - The syntax `virtual public Person` instructs the compiler to share a single, unified `Person` subobject across the inheritance paths.
  - Ambiguity is eliminated: `ta.name` and `ta.age` are directly addressable without qualification.
  - The variables `rollNo` (201201) and `employeeId` (501501) remain distinct to their intermediate paths.
  - **Constructor Rule for Virtual Bases:** When virtual inheritance is used, intermediate classes do not initialize the virtual base. The **most-derived class** (`TeachingAssistant`) is directly responsible for invoking the constructor of the virtual base class (`Person`). If `Person` lacks a default constructor, the most-derived class must explicitly call its parameterized constructor in its initializer list.

## Technical Comparison: Non-Virtual vs. Virtual Hybrid Inheritance

- **Feature Comparison:**
  - **Person Subobject Count in TeachingAssistant:** Two copies without `virtual`; exactly one shared copy with `virtual`.
  - **Access to `ta.name`:** Ambiguous without `virtual` (requires scope resolution); unambiguous and direct with `virtual`.
  - **Base-Class Sharing:** No subobject sharing without `virtual`; true subobject sharing enabled with `virtual`.
  - **Inheritance Syntax:** `class Student : public Person` vs. `class Student : virtual public Person`.
- **Real-Time Applications:**
  - **University Management Systems:** Unifies student records, faculty/employee tracking, and teaching assignments for graduate assistants.
  - **Embedded IoT Frameworks:** A hardware node inheriting from `NetworkCapability` and `SensorCapability`, sharing a root `DeviceHardware` state.
  - **Enterprise Resource Planning (ERP):** Consolidating multiple functional roles into hybrid user profiles without duplicating core user identity fields.

## Master Summary of Inheritance Classifications

- **Single Inheritance:**
  - Structural Model: A→BA \rightarrow B
  - Prototypical Example: `Person` →\rightarrow `Student`
  - Architectural Purpose: Extends a single base class.
- **Multiple Inheritance:**
  - Structural Model: A+B→CA + B \rightarrow C
  - Prototypical Example: `Academic` + `Sports` →\rightarrow `Student`
  - Architectural Purpose: Combines distinct capabilities into a unified class.
- **Multilevel Inheritance:**
  - Structural Model: A→B→CA \rightarrow B \rightarrow C
  - Prototypical Example: `LivingThing` →\rightarrow `Animal` →\rightarrow `Dog`
  - Architectural Purpose: Represents progressive domain specialization.
- **Hierarchical Inheritance:**
  - Structural Model: A→BA \rightarrow B and A→CA \rightarrow C
  - Prototypical Example: `Shape` →\rightarrow `Circle`, `Rectangle`
  - Architectural Purpose: Shares common foundational logic across distinct variants.
- **Hybrid Inheritance:**
  - Structural Model: Combination of patterns (e.g., A→B,C→DA \rightarrow B, C \rightarrow D)
  - Prototypical Example: `Person` →\rightarrow `Student`, `Employee` →\rightarrow `TeachingAssistant`
  - Architectural Purpose: Encapsulates complex real-world relationships requiring virtual base classes to prevent diamond duplication.

# Virtual Base Classes

- **Formal Definition:** A virtual base class prevents duplicate subobject instances of a common ancestor class from being included when multiple inheritance paths converge in a diamond-shaped hierarchy.
- **Direct In-Class Initialization Example:**

cpp #include using namespace std;

class Person { public: int age = 20; void display() { cout << "Age: " << age << endl; } };

class Student : virtual public Person { public: int rollNo = 101; };

class Employee : virtual public Person { public: int employeeId = 501; };

class TeachingAssistant : public Student, public Employee { };

int main() { TeachingAssistant ta; ta.age = 21; ta.display(); cout << "Roll Number: " << ta.rollNo << endl; cout << "Employee ID: " << ta.employeeId << endl; return 0; }   ```

  • Execution Output:

  Age: 21
  Roll Number: 101
  Employee ID: 501
&nbsp;&nbsp;```
- **Core Behavioral Properties:**
  - `TeachingAssistant` shares a single `Person` base instance.
  - The mutation `ta.age = 21` directly mutates the single shared instance, eliminating data divergence between the `Student` and `Employee` branches.

# Compile-Time Polymorphism (Static Polymorphism)

- **Universal Definition of Polymorphism:** "One interface, multiple implementations." An identical interface executes different behaviors based on contextual types.
- **Compile-Time Polymorphism Fundamentals:**
  - Resolution occurs entirely during compilation (early binding / static binding).
  - Execution incurs zero runtime dynamic dispatch penalty.
  - Primary mechanisms in C++ include function overloading, operator overloading, and templates.

## Function Overloading

- **Definition:** Defining multiple member functions within the same scope with identical names but differing parameter signatures (different parameter counts, types, or order).
- **Distinguishing Rules:**
  - Parameter types and parameter counts distinguish overloaded signatures.
  - **Critical Rule:** The function return type alone cannot be used to distinguish an overload.
- **Program Implementation:**

cpp #include using namespace std;

class Calculator { public: int add(int a, int b) { return a + b; }

  int add(int a, int b, int c) {
      return a + b + c;
  }

  double add(double a, double b) {
      return a + b;
  }

};

int main() { Calculator c; cout << c.add(10, 20) << endl; cout << c.add(10, 20, 30) << endl; cout << c.add(2.5, 3.5) << endl; return 0; }   ```

  • Execution Output:

  30
  60
  6
&nbsp;&nbsp;```
- **Signature Resolution Breakdown:**
  - `c.add(10, 20)`: Matches `add(int, int)` →10+20=30\rightarrow 10 + 20 = 30.
  - `c.add(10, 20, 30)`: Matches `add(int, int, int)` →10+20+30=60\rightarrow 10 + 20 + 30 = 60.
  - `c.add(2.5, 3.5)`: Matches `add(double, double)` →2.5+3.5=6.0\rightarrow 2.5 + 3.5 = 6.0.
- **Real-Time Applications:** Billing systems calculating totals across differing item volumes, or mathematical arithmetic engines.

## Operator Overloading

- **Definition:** Assigning specialized user-defined behavior to standard C++ operators when applied to class instances.
- **Mandatory Syntactic & Semantic Constraints:**
  - At least one operand must belong to a user-defined type.
  - New operator symbols cannot be invented.
  - Precedence, associativity, and arity (number of operands) are immutable.
  - **Non-Overloadable Operators:** Scope resolution (`::`), member access (`.`), pointer-to-member (`.*`), and ternary conditional (`?:`).
- **Program Implementation (Complex Number Addition):**

cpp #include using namespace std;

class Complex { public: int real, imag;

  Complex(int r, int i) {
      real = r;
      imag = i;
  }

  Complex operator+(Complex c) {
      return Complex(real + c.real, imag + c.imag);
  }

  void display() {
      cout << real << " + " << imag << "i" << endl;
  }

};

int main() { Complex c1(2, 3); Complex c2(4, 5); Complex c3 = c1 + c2; c3.display(); return 0; }   ```

  • Execution Output:

  6 + 8i
&nbsp;&nbsp;```
- **Mathematical Model:**
  - Let c1=2+3ic_1 = 2 + 3i and c2=4+5ic_2 = 4 + 5i.
  - The overloaded operator computes:
&nbsp;&nbsp;&nbsp;&nbsp;c3=c1+c2=(2+4)+(3+5)i=6+8ic_3 = c_1 + c_2 = (2 + 4) + (3 + 5)i = 6 + 8i
- **Real-Time Applications:** Matrix vector math packages, complex number libraries, financial currency arithmetic, and custom graphics vector primitives.

## Templates (Static Polymorphic Abstraction)

- **Syntax Structure:**

cpp template T add(T a, T b) { return a + b; }   ```

  • Operational Model: Generates type-specialized machine code during compilation based on the concrete types supplied at instantiation.

Runtime Polymorphism (Dynamic Polymorphism)

  • Formal Definition: Dynamic polymorphism is a mechanism where invocation of a function is resolved at runtime rather than during compilation. It is implemented in C++ via inheritance, base-class pointers or references, and virtual functions.

  • Function Overriding Mechanics:

    • Occurs when a derived class supplies its own implementation of a virtual function defined in its base class, matching the exact name and parameter signature.

  • Exhaustive Comparison: Compile-Time vs. Runtime Polymorphism:

    • Resolution Phase: Compile-Time resolves during compilation; Runtime resolves during program execution.

    • Nomenclature: Compile-Time is static polymorphism; Runtime is dynamic polymorphism.

    • Underlying Mechanisms: Compile-Time uses function overloading, operator overloading, and templates; Runtime uses virtual functions and function overriding.

    • Dispatch Criteria: Compile-Time dispatches based on static types and arguments; Runtime dispatches based on the underlying object's runtime type.

    • Structural Prerequisites: Compile-Time does not require an inheritance hierarchy; Runtime typically requires inheritance and base pointers/references.

    • Performance Profile: Compile-Time incurs zero runtime dispatch overhead; Runtime incurs indirection overhead through virtual tables (vTable\text{vTable}) and virtual pointers (vPtr\text{vPtr}).

    • Representative Syntax: add(10, 20) vs. ptr->calculateSalary().

Employee Payroll Management System Implementation

  • C++ Source Code:

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

  class Employee {
  public:
      string name;
      int employeeId;
      double basicPay;

      virtual void calculateSalary() {
          cout << "Calculating salary" << endl;
      }
  };

  class PermanentEmployee : public Employee {
  public:
      void calculateSalary() override {
          double salary = basicPay + 10000 + 5000;
          cout << "Name: " << name << endl;
          cout << "Employee ID: " << employeeId << endl;
          cout << "Basic Pay: Rs. " << basicPay << endl;
          cout << "Monthly Salary: Rs. " << salary << endl;
      }
  };

  class Intern : public Employee {
  public:
      void calculateSalary() override {
          double stipend = basicPay;
          cout << "Name: " << name << endl;
          cout << "Employee ID: " << employeeId << endl;
          cout << "Basic Pay: Rs. " << basicPay << endl;
          cout << "Monthly Stipend: Rs. " << stipend << endl;
      }
  };

  int main() {
      PermanentEmployee p;
      p.name = "Arun";
      p.employeeId = 101;
      p.basicPay = 30000;

      Intern i;
      i.name = "Priya";
      i.employeeId = 102;
      i.basicPay = 10000;

      Employee* ptr;

      ptr = &p;
      ptr->calculateSalary();
      cout << endl;

      ptr = &i;
      ptr->calculateSalary();

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text Name: Arun Employee ID: 101 Basic Pay: Rs. 30000 Monthly Salary: Rs. 45000

Name: Priya Employee ID: 102 Basic Pay: Rs. 10000 Monthly Stipend: Rs. 10000   ```

  • Mathematical Computations:

    • Permanent Employee (p):     Monthly Salary=Basic Pay+10000+5000=30000+10000+5000=45000\text{Monthly Salary} = \text{Basic Pay} + 10000 + 5000 = 30000 + 10000 + 5000 = 45000     (Where the additional ₹10,000 and ₹5,000 values serve as illustrative allowances).

    • Intern (i):     Monthly Stipend=Basic Pay=10000\text{Monthly Stipend} = \text{Basic Pay} = 10000

  • Runtime Polymorphic Dispatch: Even though ptr is statically declared as Employee*, the invocation ptr->calculateSalary() inspects the runtime identity of the referenced instance, selecting PermanentEmployee::calculateSalary or Intern::calculateSalary dynamically.

Virtual Functions and Dynamic Dispatch

  • Formal Definition: A virtual function is a base class member function declared with the virtual specifier that allows derived class overrides to be invoked polymorphically when called via a base-class pointer or reference.

  • The override Specifier: While syntactically optional in modern C++, using override enables compile-time verification that the declared member matches a virtual function signature in the base class, catching typo bugs early.

  • Program Implementation (Shape Rendering Pipeline):

  #include <iostream>
  using namespace std;

  class Shape {
  public:
      virtual void draw() {
          cout << "Drawing a shape" << endl;
      }
      virtual ~Shape() = default;
  };

  class Circle : public Shape {
  public:
      void draw() override {
          cout << "Drawing a circle" << endl;
      }
  };

  class Rectangle : public Shape {
  public:
      void draw() override {
          cout << "Drawing a rectangle" << endl;
      }
  };

  int main() {
      Circle c;
      Rectangle r;
      Shape* ptr;

      ptr = &c;
      ptr->draw();

      ptr = &r;
      ptr->draw();

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text Drawing a circle Drawing a rectangle   ```

  • Architectural Benefits: Eliminates brittle conditional branches (such as switch or if-else chains on type enums), decouples interfaces from concrete implementations, and enables extensible plugin architectures.

Pure Virtual Functions and Abstract Classes

  • Pure Virtual Function Definition: A virtual function explicitly defined with = 0 in its declaration. It specifies an interface contract without providing an implementation in the declaring class.

  • Abstract Class Definition: A class containing at least one un-overridden pure virtual function. Abstract classes cannot be directly instantiated.

  • Concrete Class Transition Rule: A derived class remains abstract until it implements all inherited pure virtual functions. Implementing every pure virtual function transitions the derived class into a concrete class.

Area Calculation Implementation

  • C++ Source Code:

  #include <iostream>
  using namespace std;

  class Shape {
  public:
      virtual void area() = 0;
      virtual ~Shape() = default;
  };

  class Rectangle : public Shape {
  public:
      int length = 10;
      int breadth = 5;

      void area() override {
          cout << "Area of Rectangle: " << length * breadth << endl;
      }
  };

  int main() {
      Rectangle r;
      r.area();
      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text Area of Rectangle: 50   ```

  • Computational Formulation:   Area=length×breadth=10×5=50\text{Area} = \text{length} \times \text{breadth} = 10 \times 5 = 50

  • Direct Instantiation Restrictions: Writing Shape s; results in a compilation failure because Shape contains a pure virtual function (virtual void area() = 0;).

Enterprise Payroll Pipeline Using Abstract Base Classes

  • C++ Source Code:

  #include <iostream>
  using namespace std;

  class Employee {
  public:
      double basicPay;

      Employee(double basic) {
          basicPay = basic;
      }

      virtual void calculateSalary() = 0;
      virtual ~Employee() = default;
  };

  class PermanentEmployee : public Employee {
  public:
      PermanentEmployee(double basic) : Employee(basic) {}

      void calculateSalary() override {
          double hra = basicPay * 0.20;
          double da = basicPay * 0.10;
          double salary = basicPay + hra + da;

          cout << "Permanent Employee Salary Details" << endl;
          cout << "Basic Pay: Rs. " << basicPay << endl;
          cout << "HRA: Rs. " << hra << endl;
          cout << "DA: Rs. " << da << endl;
          cout << "Total Salary: Rs. " << salary << endl;
      }
  };

  class Intern : public Employee {
  public:
      Intern(double basic) : Employee(basic) {}

      void calculateSalary() override {
          double stipend = basicPay;
          cout << "Intern Salary Details" << endl;
          cout << "Basic Pay: Rs. " << basicPay << endl;
          cout << "Total Stipend: Rs. " << stipend << endl;
      }
  };

  int main() {
      PermanentEmployee p(40000);
      Intern i(10000);

      p.calculateSalary();
      cout << endl;
      i.calculateSalary();

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text Permanent Employee Salary Details Basic Pay: Rs. 40000 HRA: Rs. 8000 DA: Rs. 4000 Total Salary: Rs. 52000

Intern Salary Details Basic Pay: Rs. 10000 Total Stipend: Rs. 10000   ```

  • Mathematical Salary Formulations:

    • Permanent Employee (Basic Pay=40000\text{Basic Pay} = 40000):     HRA=Basic Pay×0.20=40000×0.20=8000\text{HRA} = \text{Basic Pay} \times 0.20 = 40000 \times 0.20 = 8000     DA=Basic Pay×0.10=40000×0.10=4000\text{DA} = \text{Basic Pay} \times 0.10 = 40000 \times 0.10 = 4000     Total Salary=Basic Pay+HRA+DA=40000+8000+4000=52000\text{Total Salary} = \text{Basic Pay} + \text{HRA} + \text{DA} = 40000 + 8000 + 4000 = 52000     (Percentages for HRA (20%20\%) and DA (10%10\%) represent pedagogical illustrative values).

    • Intern (Basic Pay=10000\text{Basic Pay} = 10000):     Total Stipend=Basic Pay=10000\text{Total Stipend} = \text{Basic Pay} = 10000

  • Key Abstract Class Properties: Abstract classes can declare member variables, parameterized constructors, non-virtual helper functions, and virtual destructors. Only direct instantiation is forbidden.

Virtual Destructors

  • Formal Definition: A virtual destructor is a destructor declared with the virtual keyword in a base class. It guarantees that when a derived-class object is destroyed via a base-class pointer, the destructors execute in the correct hierarchical order: the derived destructor runs first to release derived resources, followed by the base destructor.

  • Hazard of Non-Virtual Destructors: Deleting a derived-class instance through a pointer to a base class with a non-virtual destructor results in undefined behavior according to the C++ standard, typically causing partial destruction and resource leaks (e.g., dangling file handles, unreleased dynamic heap buffers, or leaked sockets).

  • Destructor Access Guidelines: A polymorphic base class should provide either a public virtual destructor or a protected non-virtual destructor (if deleting derived instances through the base pointer is intentionally forbidden).

  • Program Implementation:

  #include <iostream>
  using namespace std;

  class Base {
  public:
      virtual ~Base() {
          cout << "Base destructor" << endl;
      }
  };

  class Derived : public Base {
  public:
      ~Derived() override {
          cout << "Derived destructor" << endl;
      }
  };

  int main() {
      Base* ptr = new Derived();
      delete ptr;
      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text Derived destructor Base destructor   ```

  • Destruction Execution Flow:

    • Base* ptr = new Derived();: Allocates derived-class instance on the heap.

    • delete ptr;: Inspects Base's destructor, finds it marked virtual, dispatches to Derived::~Derived(), and then invokes Base::~Base().

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

  • Mechanics of Dynamic Dispatch:

    • Virtual Pointer (vPtr\text{vPtr}): A hidden pointer embedded by the compiler inside every instance of a class that contains virtual functions. It points directly to the class's virtual table.

    • Virtual Table (vTable\text{vTable}): A compiler-generated static array of function pointers created for each polymorphic class. Each entry points to the most-derived implementation of a virtual function visible to that class.      

      Virtual pointer (vPtr) mapping to virtual table (vTable) entries across base and derived objects

           

      Dynamic dispatch call execution flow using base-class pointers and vTables
  • Multi-Level Inheritance Virtual Dispatch Program:

  #include <iostream>
  using namespace std;

  class Base {
  public:
      virtual void function1() {
          cout << "Base::function1()" << endl;
      }
      virtual void function2() {
          cout << "Base::function2()" << endl;
      }
      virtual void function3() {
          cout << "Base::function3()" << endl;
      }
      virtual ~Base() = default;
  };

  class Derived1 : public Base {
  public:
      void function1() override {
          cout << "Derived1::function1()" << endl;
      }
      // function2() and function3() are inherited
  };

  class Derived2 : public Derived1 {
  public:
      void function2() override {
          cout << "Derived2::function2()" << endl;
      }
      // function1() and function3() are inherited
  };

  int main() {
      Base b;
      Derived1 d1;
      Derived2 d2;
      Base* ptr;

      cout << "----- Base Object -----" << endl;
      ptr = &b;
      ptr->function1();
      ptr->function2();
      ptr->function3();

      cout << "
----- Derived1 Object -----" << endl;
      ptr = &d1;
      ptr->function1();
      ptr->function2();
      ptr->function3();

      cout << "
----- Derived2 Object -----" << endl;
      ptr = &d2;
      ptr->function1();
      ptr->function2();
      ptr->function3();

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output:**

text ----- Base Object ----- Base::function1() Base::function2() Base::function3()

----- Derived1 Object ----- Derived1::function1() Base::function2() Base::function3()

----- Derived2 Object ----- Derived1::function1() Derived2::function2() Base::function3()   ```

  • Internal Table Resolution Breakdown:

    • Base vTable\text{vTable}: Contains &Base::function1, &Base::function2, and &Base::function3.

    • Derived1 vTable\text{vTable}: Contains &Derived1::function1 (overridden), &Base::function2 (inherited), and &Base::function3 (inherited).

    • Derived2 vTable\text{vTable}: Contains &Derived1::function1 (inherited from Derived1), &Derived2::function2 (overridden), and &Base::function3 (inherited from Base).

    • Calling ptr->function2() on d2 dereferences d2's vPtr, locates Derived2's vTable, and invokes Derived2::function2() directly.

Run-Time Type Information (RTTI), Dynamic Cast, and Typeid

  • RTTI Concept: Run-Time Type Information (RTTI\text{RTTI}) is a mechanism that allows the concrete type of an object to be deduced at runtime, primarily when manipulated via base-class pointers or references.

  • Polymorphic Base Prerequisite: Dynamic type identification via RTTI\text{RTTI} requires the target class to be polymorphic (possessing at least one virtual function or a virtual destructor).

  • Core Operators:

    • dynamic_cast: Performs runtime-checked type conversions down or across class hierarchies.

    • typeid: Queries runtime type information, returning a constant reference to a std::type_info object defined in <typeinfo>.

Structural Comparison: Virtual Functions vs. RTTI

  • Primary Purpose: Virtual Functions select an overridden method dynamically; RTTI\text{RTTI} discovers the concrete type of an object.

  • Typical Application: Virtual Functions implement behavioral polymorphism; RTTI\text{RTTI} performs safe downcasting or type inspection when an operation is outside the base-class interface.

  • Underlying Mechanism: Virtual Functions use indirect table dispatch via vPtr/vTable\text{vPtr} / \text{vTable}; RTTI\text{RTTI} inspects type descriptor metadata associated with the class vTable\text{vTable}.

  • Representative Usage: ptr->display(); vs. typeid(*ptr).

Combined RTTI Demonstration Program

  • C++ Source Code:

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

  class Employee {
  public:
      virtual void work() {
          cout << "Employee is working" << endl;
      }
      virtual ~Employee() = default;
  };

  class Manager : public Employee {
  public:
      void work() override {
          cout << "Manager is managing the team" << endl;
      }
      void conductMeeting() {
          cout << "Manager is conducting a meeting" << endl;
      }
  };

  class Developer : public Employee {
  public:
      void work() override {
          cout << "Developer is writing code" << endl;
      }
      void writeCode() {
          cout << "Developer is developing software" << endl;
      }
  };

  int main() {
      Manager m;
      Employee* ptr = &m;

      // Virtual function dispatch
      ptr->work();

      // RTTI using typeid
      cout << "Object type: " << typeid(*ptr).name() << endl;

      // Runtime type checking using dynamic_cast
      Manager* mgr = dynamic_cast<Manager*>(ptr);
      if (mgr != nullptr) {
          mgr->conductMeeting();
      }

      return 0;
  }
&nbsp;&nbsp;```
- **Execution Output (Standard GCC):**

text Manager is managing the team Object type: 7Manager Manager is conducting a meeting   `` &nbsp;&nbsp;*(Note: Output fromtypeid.name()depends on the compiler's ABI name-mangling scheme; a GCC binary returns7Manager, whereas MSVC returnsclass Manager`).*

The dynamic_cast Operator

  • Formal Definition: A C++ type-casting operator used to safely convert a pointer or reference from a base class to a derived class at runtime.

  • Failure Modes:

    • Pointers: Returns nullptr if the underlying object cannot be cast to the target derived type.

    • References: Throws a std::bad_cast exception on failure.

  • Syntax Structure:

  Derived *ptr = dynamic_cast<Derived*>(basePtr);
  Derived &ref = dynamic_cast<Derived&>(baseRef);
&nbsp;&nbsp;```
- **Step-by-Step Execution Flow:**
&nbsp;&nbsp;
&nbsp;&nbsp;![Flowchart of dynamic_cast runtime verification and pointer conversion](https://assets.knowt.com/pdf-flow-prod/87bc7ad5-6c32-4e53-8acd-df96a2abaae0-figures/9.png)

- **Interactive Downcasting Implementation:**

cpp #include using namespace std;

class Employee { public: virtual void display() { cout << "Employee details" << endl; } virtual ~Employee() = default; };

class PermanentEmployee : public Employee { public: void showSalary() { cout << "Monthly salary: 50000" << endl; } };

class ContractEmployee : public Employee { public: void showContract() { cout << "Contract duration: 12 months" << endl; } };

int main() { Employee *emp; PermanentEmployee p; ContractEmployee c; int choice;

  cout << "1. Permanent Employee" << endl;
  cout << "2. Contract Employee" << endl;
  cout << "Enter choice: ";
  cin >> choice;

  if (choice == 1)
      emp = &p;
  else if (choice == 2)
      emp = &c;
  else {
      cout << "Invalid choice" << endl;
      return 0;
  }

  if (dynamic_cast<PermanentEmployee*>(emp)) {
      PermanentEmployee *ptr = dynamic_cast<PermanentEmployee*>(emp);
      ptr->showSalary();
  }
  else if (dynamic_cast<ContractEmployee*>(emp)) {
      ContractEmployee *ptr = dynamic_cast<ContractEmployee*>(emp);
      ptr->showContract();
  }

  return 0;

}   ```

  • Execution Traces:

    • Sample Execution 1: Input: 1 ```text

    1. Permanent Employee

    2. Contract Employee Enter choice: 1 Monthly salary: 50000     ```

  • Sample Execution 2: Input: 2 ```text

    1. Permanent Employee

    2. Contract Employee Enter choice: 2 Contract duration: 12 months     ```

The typeid Operator

  • Formal Definition: A built-in C++ operator that retrieves type metadata for any expression or type at compile-time or runtime. Defined in <typeinfo>, it returns a reference to an immutable std::type_info instance.

  • Evaluation Mechanism: For polymorphic types, typeid(*ptr) inspects runtime type descriptors referenced by the object's vTable\text{vTable}. For non-polymorphic types, it evaluates the static type at compile time.

  • Syntax Structure:

  typeid(expression)
  cout << typeid(expression).name();
&nbsp;&nbsp;```
- **Execution Flowchart:**
&nbsp;&nbsp;
&nbsp;&nbsp;![Flowchart of typeid object examination and comparison process](https://assets.knowt.com/pdf-flow-prod/87bc7ad5-6c32-4e53-8acd-df96a2abaae0-figures/10.png)

- **Type Inspection and Equality Checking Implementation:**

cpp #include #include using namespace std;

class Employee { public: virtual void display() { cout << "Employee details" << endl; } };

class Manager : public Employee { public: void display() override { cout << "Manager details" << endl; } };

class Developer : public Employee { public: void display() override { cout << "Developer details" << endl; } };

int main() { Employee *emp; Manager m; Developer d; int choice;

  cout << "1. Manager" << endl;
  cout << "2. Developer" << endl;
  cout << "Enter choice: ";
  cin >> choice;

  if (choice == 1)
      emp = &m;
  else if (choice == 2)
      emp = &d;
  else {
      cout << "Invalid choice";
      return 0;
  }

  if (typeid(*emp) == typeid(Manager))
      cout << "Object type: Manager";
  else if (typeid(*emp) == typeid(Developer))
      cout << "Object type: Developer";

  return 0;

}   ```

  • Execution Traces:

    • Sample Execution 1: Input: 1 →\rightarrow Output: Object type: Manager.

    • Sample Execution 2: Input: 2 →\rightarrow Output: Object type: Developer.

Technical Comparison: dynamic_cast vs. typeid

  • Functional Scope: dynamic_cast verifies downcasting validity and performs pointer conversion; typeid inspects and compares runtime types without performing conversions.

  • Cast Failure Handling: dynamic_cast returns nullptr for failed pointer casts; typeid does not cast, so pointer conversion is not applicable.

  • Primary Use Case: dynamic_cast is used to safely access derived-class members; typeid is used to verify exact type equality or retrieve type names.

Real-World Applications Summary Across Core Topics

  • Single Inheritance Applications: College registries (Person →\rightarrow Student), workforce systems (Person →\rightarrow Employee), clinic registries (Person →\rightarrow Doctor).

  • Multiple Inheritance Applications: Composite academic reporting, multi-protocol devices (Wi-Fi and Bluetooth), hybrid office peripherals (printer-scanners).

  • Multilevel Inheritance Applications: Vehicle powertrain telemetry (Vehicle →\rightarrow Car →\rightarrow ElectricCar), banking tier structures (Account →\rightarrow SavingsAccount →\rightarrow PremiumSavingsAccount), cybersecurity auditing (SecurityEvent →\rightarrow NetworkEvent →\rightarrow SuspiciousNetworkEvent).

  • Hierarchical Inheritance Applications: Vector graphics shape models (Shape →\rightarrow Circle, Rectangle, Triangle), institutional user hierarchies (Person →\rightarrow Student, Faculty), transportation categorizations (Vehicle →\rightarrow Car, Bus, Motorcycle).

  • Virtual Base Classes Applications: University systems consolidating student and employee records into teaching assistant roles; multi-capability IoT sensor networks sharing common hardware descriptors.

  • Compile-Time Polymorphism Applications: Overloaded mathematical utility libraries, flexible billing engines processing variable-length parameter sets, custom algebraic matrices.

  • Runtime Polymorphism Applications: Heterogeneous payroll processing via a shared base interface, extensible graphics drawing engines, transaction processing handling UPI, credit cards, and net-banking polymorphically.

  • Abstract Classes & Interfaces Applications: Standardized database connectivity drivers (connect(), execute()), cybersecurity vulnerability scanning pipelines (scan(), analyze()), financial transaction interfaces.

  • Virtual Destructors Applications: Dynamic resource management frameworks managing hardware sockets, OS file descriptors, and allocated memory across complex class hierarchies.

  • RTTI, dynamic_cast & typeid Applications: Dynamic role verification in employee databases, identifying concrete account subtypes in banking engines, runtime actor-component dispatch in game development.