OOP: Inheritance & Overriding

⚡ C++ Lesson 13 Intermediate

Inheritance lets child classes inherit properties from parent classes. C++ uses the virtual keyword to implement runtime overrides and polymorphism.

1 Virtual Keywords & Dynamic Dispatch

By default, C++ binds methods at compile time based on the reference type. To override a method dynamically at runtime, you must declare it as **`virtual`** in the parent class. If a parent reference points to a child class object, the virtual keyword ensures that the child subclass implementation executes.

2 Inheritance and Virtual Overriding Code

Let's run a program illustrating inheritance and virtual method overriding:

C++ — Inheritance and Polymorphism ▶ Run Code
#include <iostream>
#include <string>

class Animal {
public:
    // Declare method as virtual to allow overriding at runtime
    virtual void makeNoise() const {
        std::cout << "Generic animal sound.\n";
    }
    virtual ~Animal() = default; // virtual destructor is required for base classes
};

class Dog : public Animal {
public:
    void makeNoise() const override { // override keyword validates signature matches parent
        std::cout << "Woof! Woof!\n";
    }
};

int main() {
    // Polymorphic reference: parent type holding a child subclass object
    Animal *myAnimal = new Dog();
    
    // Virtual keyword triggers runtime dispatch, executing Dog's makeNoise()
    myAnimal->makeNoise(); 

    delete myAnimal;
    return 0;
}
3 Code Challenge
Challenge: Create an abstract base class called `Vehicle` with a pure virtual method `void startEngine() = 0;`. Create a subclass `Truck` that overrides this method to print "Truck engine roaring". Test your implementation.