override Keyword in C++

C++Server Side ProgrammingProgramming

The function overriding is the most common feature of C++. Basically function overriding means redefine a function which is present in the base class, also be defined in the derived class. So the function signatures are the same but the behavior will be different.

But there may be a situation when a programmer makes a mistake while overriding that function. Like if the signature is not the same, then that will be treated as another function, but not the overridden method or that. In that case, we can use the override keyword. This keyword is introduced in C+ +11. When the compiler finds this kind of keyword, it can understand that this is an overridden version of the same class.

Let us see the example to understand the concept.

Example

#include <iostream>
using namespace std;
class BaseClass{
   public:
      virtual void display() {
         cout << "Displaying from Base Class\n";
      }
};
class DerivedClass : public BaseClass{
   public:
      void display() {
         cout << "Displaying from Derived Class\n";
      }
};
main() {
   BaseClass *b_ptr;
   b_ptr = new DerivedClass();
   b_ptr->display();
}

Output

Displaying from Derived Class

In this case the program is working fine as the signatures are the same. In the following example, the signature will be different. For the override keyword, it will generate an error.

Example

#include <iostream>
using namespace std;
class BaseClass{
   public:
      virtual void display() {
         cout << "Displaying from Base Class\n";
      }
};
class DerivedClass : public BaseClass{
   public:
      void display(int x) override{
         cout << "Displaying from Derived Class\n";
      }
};
main() {
   BaseClass *b_ptr;
   b_ptr = new DerivedClass();
   b_ptr->display();
}

Output

[Error] 'void DerivedClass::display(int)' marked override, but does not override

In this case, the program is working fine as the signatures are the same. In the following example, the signature will be different. For the override keyword, it will generate error.

raja
Published on 02-May-2019 12:29:44
Advertisements