Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is the point of keyword override if child class member function will always be called?

#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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading