0
0
C++programming~5 mins

Method overriding in C++

Choose your learning style9 modes available
Introduction
Method overriding lets a child class change how a method works from its parent class. This helps customize behavior without changing the original code.
You want a child class to do something different when a method is called.
You have a general method in a parent class but need specific actions in child classes.
You want to reuse code but change only parts of it in subclasses.
You want to make your program easier to extend and maintain.
Syntax
C++
class Parent {
public:
    virtual void methodName() {
        // parent method code
    }
};

class Child : public Parent {
public:
    void methodName() override {
        // child method code
    }
};
Use the keyword virtual in the parent class method to allow overriding.
Use override in the child class method to make sure you are actually overriding a parent method.
Examples
The Dog class changes the sound method to print "Bark" instead of "Some sound".
C++
class Animal {
public:
    virtual void sound() {
        std::cout << "Some sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Bark" << std::endl;
    }
};
Car overrides start to show a more specific message.
C++
class Vehicle {
public:
    virtual void start() {
        std::cout << "Vehicle starting" << std::endl;
    }
};

class Car : public Vehicle {
public:
    void start() override {
        std::cout << "Car starting" << std::endl;
    }
};
Sample Program
This program shows how the Child class changes the greet method. When we call greet on a Parent pointer to a Child object, the Child's greet runs.
C++
#include <iostream>

class Parent {
public:
    virtual void greet() {
        std::cout << "Hello from Parent" << std::endl;
    }
};

class Child : public Parent {
public:
    void greet() override {
        std::cout << "Hello from Child" << std::endl;
    }
};

int main() {
    Parent* p = new Parent();
    Parent* c = new Child();

    p->greet();  // Calls Parent greet
    c->greet();  // Calls Child greet because of overriding

    delete p;
    delete c;
    return 0;
}
OutputSuccess
Important Notes
If you forget the virtual keyword in the parent, overriding won't work as expected.
Using override helps catch mistakes if the method signature doesn't match the parent.
Always delete objects created with new to avoid memory leaks.
Summary
Method overriding lets child classes change parent class methods.
Use virtual in parent and override in child for safe overriding.
It helps customize behavior while reusing code.