C++ Function Overriding

Function overriding in C++ occurs when a derived class provides a specific implementation for a member function that is already defined in its base class. The overridden function in the derived class must have the same name, return type, and parameters as the function in the base class. Function overriding is used to achieve run-time polymorphism with the help of virtual functions.

Syntax

class Base {
public:
    virtual return_type functionName(parameters) {
        // Base class implementation
    }
};

class Derived : public Base {
public:
    return_type functionName(parameters) override {
        // Derived class implementation
    }
};

Example: Function Overriding

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() { // Virtual function
        cout << "Some generic sound" << endl;
    }
};

class Dog : public Animal {
public:
    void sound() override { // Function overriding
        cout << "Woof Woof" << endl;
    }
};

int main() {
    Animal *a1;
    Dog d;

    a1 = &d;
    a1->sound(); // Calls overridden function in Dog

    return 0;
}

Output

Woof Woof

Important Notes

  • The base class function must be declared virtual to allow overriding.
  • The derived class function should use the override keyword for clarity and safety.
  • Function overriding enables run-time polymorphism where the function called depends on the object type at runtime.

Next Topic

Next, learn about Abstraction in C++.