override
It is contextual keyword(we can still use it as identifier)is used in derived class with overriding function(function is virtual in base class and its present in derived class with same signature). It is added in c++11 features list. It did not enhance any functionality but it enhance the user experience.
Advantage:
- If “override” keyword is added in function declaration in derive class then by just looking the function declaration, we will get to know that it is overridden function otherwise we need to check the base class declaration because virtual keyword is NOT mandatory in function deceleration in derive class.
- [This is hypothetical condition] If someone remove the virtual keyword from function declaration in base class then function behaviour will be changed(function call will depend upon type of pointer instead of type of object). If “override” keyword would have been added in function declaration in derived class then we would have got “compilation error”.
- By mistake, If we add override keyword in non virtual function or wrong function(different signature) in derived class then we will get compilation error and we will get to know that we are overriding wrong function and after that we can correct it.
Complete source code and example:
#include<iostream> #include<memory> class Base { public: virtual void fun1(){std::cout<<"Base fun1"<<std::endl;} //virtual void fun2(){std::cout<<"Base fun2"<<std::endl;} //Removed the virtual keyword from fun2 and I got different behaviour void fun2(){std::cout<<"Base fun2"<<std::endl;} }; class Derived:public Base { public: //Just looking at fun1, I got to know, its virtual function due to override //If virtual is removed from base then I will get compilation error void fun1()override {std::cout<<"Derived fun1"<<std::endl;} //I am not getting, is it virtual or not because virtual keyword is not //neccessary in declarion so I need to check in base class //If virtual is removed from base then behaviour will be changed void fun2() {std::cout<<"Derived fun2"<<std::endl;} }; int main() { std::cout<<"Override"<<std::endl; std::unique_ptr<Base> upB = std::make_unique<Derived>(); upB->fun1(); upB->fun2(); return 0; }
Output:
Override Derived fun1 Base fun2