What is Overriding in C++

By | November 26, 2024

Write a program in C++ to depict the concept of overriding or Dynamic polymorphism.

Overriding is a type of polymorphism. Polymorphism in OOP languages means to take more than one form.
Virtual functions in C++ are functions that do not have an actual implementation, these are written in the base class to be overridden in derived class. When a member function is virtual the class becomes Abstract.
Take a look at the code given below;

Here when the base class pointer points to derived class object without the keyword ‘virtual’ the compiler only checks the type of the pointer and not the type of the object therefore calls the function of the base class. But when ‘virtual’ is added before the definition of void function the compiler calls the Derived class function and prints the required result. This is a feature of Object oriented programming languages called Dynamic Polymorphism or Overriding.

// Write C++ code here
#include <iostream>
using namespace std;

class Base {
    int x;
public:
    Base() {
        cout << "Base class Constructor called" << endl;
    }
    virtual void function() {
        cout << "Base class function called" << endl;
    }
};

class Derived : public Base {
    int y;
public:
    Derived() {
        cout << "Derived class Constructor called" << endl;
    }
    void function() override {
        cout << "Derived class function called" << endl;
    }
};

int main() {
    Base *b, b1;
    cout << endl;

    Derived *d, d1;

    // Base class pointer points to base class object
    b = &b1;
    // Derived class pointer points to derived class object
    d = &d1;

    cout << endl;
    b->function();
    d->function();

    // Base class pointer points to derived class object
    b = &d1;
    cout << endl;
    b->function();

    return 0;
}

Output:

Base class Constructor called

Base class Constructor called
Derived class Constructor called

Base class function called
Derived class function called

Derived class function called
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.