C++ Function Overriding

ww‮w‬.theitroad.com

Function overriding is a feature in C++ that allows derived classes to provide their own implementation of a method that is already defined in the base class. Function overriding is a way to implement polymorphism in C++.

To override a method in a derived class, you need to declare the method in the base class as virtual. When a method is declared as virtual in the base class, it becomes a virtual function, which means that it can be overridden in the derived classes.

The derived class must also declare the overridden method as virtual, using the virtual keyword. This is not strictly necessary, but it is good practice to make it clear that the derived class is intentionally overriding a virtual function from the base class.

Here's an example:

class Animal {
public:
    virtual void speak() {
        std::cout << "Animal speaks." << std::endl;
    }
};

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

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

int main() {
    Animal* a = new Animal();
    a->speak();  // "Animal speaks."

    Animal* b = new Dog();
    b->speak();  // "Dog barks."

    Animal* c = new Cat();
    c->speak();  // "Cat meows."
}

In this example, we have a base class Animal with a virtual method speak(). We also have two derived classes, Dog and Cat, that override the speak() method with their own implementation.

In the main() function, we create three objects of type Animal, Dog, and Cat, but we assign them to pointers of type Animal. This allows us to call the speak() method on these objects, even though they're of different types. The output of this code will be the execution of the appropriate derived class implementation of the speak() method, based on the actual type of the object being pointed to.