0

The keyword virtual allows the derived class to override in need of polymorphism, and this can be down with or without the keyword override. How does adding override affect the program?

example code:

#include <iostream>
using namespace std;

class Base {
public:
    void Print() {who();}
    virtual void who() { cout << "I am Base\n"; }
};
class Derived_A : public Base {
public:
    void who() { cout << "I am Derived_A\n"; }
};
class Derived_B : public Base {
public:
    virtual void who() override { cout << "I am Derived_B\n"; }
};

int main()
{
    Base b;
    b.Print(); //-> return "I am Base"

    Base* ptr = new Derived_A();
    ptr->Print(); // was expecting "I am Base" instead returns "I am Derived_A"

    Base* ptr1 = new Derived_B();
    ptr1->Print(); // expecting "I am Derived_B" and surely returns "I am Derived_B"

    return 0;
}

1 Answers1

1

Adding override to a member function does not change the way your program works in any way. You merely tell the compiler that you want to override a base class function and that you'd like to get a compilation error if you somehow made a mistake, thinking that you are overriding a function, when you are in fact not.

Example:

class Base {
public:
    virtual void foo(int) {}
};

class Derived : public Base {
public:
    void foo(double) override {} // compilation error
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • so polymorphism of class inherence just come regardless of override keyword? – jojo_Aero_smith_the_dummy Mar 27 '22 at 07:44
  • @jojo_Aero_smith_the_dummy Yes. It's just for you as a programmer to feel extra secure that you've actually successfully overridden a `virtual` function. I personally would like `override` to be mandatory - but that would be a breaking change. – Ted Lyngmo Mar 27 '22 at 07:46