#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;
}
I have a question on the working of keyword override. The override marks the derived function to use. If I don’t mark to use the derived class function, then why Base* pointer calls the derived class function instead of Base class function?
>Solution :
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
};