08 Feb C++ Overriding
In C++, overriding is a feature that allows a derived class to provide a specific implementation of a function that is already defined in its base class. This is useful in cases where the derived class needs to modify or extend the behavior of the base class method.
Overriding is done by defining a function in the derived class with the same name, return type, and parameters as the function in the base class, but it must also use the virtual keyword in the base class to indicate that the method can be overridden.
Let us see the syntax of the override keyword:
The override comes after the function signature but before the function body:
Let us now see an example to override a virtual function in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> using namespace std; class Base { public: virtual void display() { cout << "Display method of Base class" << endl; } }; class Derived : public Base { public: void display() override { // `override` keyword indicates that this function is meant to override Base::display() cout << "Display method of Derived class" << endl; } }; int main() { Derived derivedObj; derivedObj.display(); // Calls the overridden method in Derived class return 0; } |
Here is the output:
1 2 3 |
Display method of Derived class |
In the above code, the Base class has a virtual display() function, and the Derived class overrides this function with its own implementation.
When derivedObj.display() is called, it executes the overridden function in the Derived class, displaying “Display method of Derived class“.
Here,
- class Base: Defines a class named Base.
- virtual void display(): Declares a virtual function display() in the Base class. The virtual keyword indicates that this function can be overridden in a derived class.
- class Derived : public Base: Defines a class named Derived that inherits from the Base class.
- void display() override: Overrides the display() function in the Base class. The override keyword ensures that this function is intended to override a virtual function in the base class.
- Derived derivedObj: Creates an object of the Derived class named derivedObj.
- derivedObj.display(): Calls the display() method of the Derived class. Because display() is overridden in the Derived class, this calls the overridden method rather than the one in the Base class.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments