'what is the use of keyword override in virtual function of child class? [duplicate]
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;
}
Solution 1:[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
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |