Home C++ Tutorial C++ Programs that demonstrate the concept of function overriding

C++ Programs that demonstrate the concept of function overriding

by Anup Maurya
24 minutes read

In this article, you’ll learn about how to make C++ program that demonstrate the concept of function overriding with explanation.

What is function overriding?

Function overriding in C++ is termed as the redefinition of base class function in its derived class with the same signature i.e. return type and parameters. It falls under the category of Runtime Polymorphism.

C++ Programs that demonstrate the concept of function overriding

#include <iostream>

class Animal {
public:
    virtual void makeSound() {
        std::cout << "The animal makes a generic sound." << std::endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "The dog barks." << std::endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "The cat meows." << std::endl;
    }
};

int main() {
    Animal *animal = new Animal();
    Dog *dog = new Dog();
    Cat *cat = new Cat();

    animal->makeSound();
    dog->makeSound();
    cat->makeSound();

    delete animal;
    delete dog;
    delete cat;

    return 0;
}

In this program, we define a base class Animal with a virtual function makeSound(). The function is defined with the virtual keyword, indicating that it can be overridden by subclasses.

We then define two subclasses Dog and Cat, both of which inherit from Animal. The subclasses override the makeSound() function with their own implementation.

In the main function, we create instances of Animal, Dog, and Cat, and call their makeSound() function. Because the makeSound() function is virtual, the appropriate implementation for each object is called, based on the type of the object.

The output of the program is:

The animal makes a generic sound.
The dog barks.
The cat meows.

That’s an example of how to demonstrate the concept of function overriding in C++. Function overriding allows a subclass to provide a different implementation of a virtual function than its superclass, and allows for polymorphism by allowing different objects to be treated as instances of their respective subclasses.

related posts

Leave a Comment