C++ Function Overriding
Can we have functions in the base class and derived class with the same name and same signature?
Yes, In C++ we can define a function with the same name and signature in the derived class. And in such a situation when we invoke the function using derived class object, then only the derived class member gets invokes and not the base class member function.
This process is known as function overriding
This concept is used to achieve runtime polymorphism. It enables you to provide specific/different implementation of the function which is already provided by its base class.
Difference between function overloading and function overriding
function overloading | function overriding |
Function Overloading happens in the same class when we declare same functions with different arguments in the same class. | Function Overriding is happens in the child class when child class overrides parent class function. |
In function overloading function signature should be different for all the overloaded functions. | In function overriding the signature of both the functions (overriding function and overridden function) should be same. |
Overloading happens at the compile time thats why it is also known as compile time polymorphism | while overriding happens at run time which is why it is known as run time polymorphism. |
In function overloading we can have any number of overloaded functions. | In function overriding we can have only one overriding function in the child class. |
Example of function overriding
Both base class derived class have a function with the same name “display()”
//function overriding #include<iostream> using namespace std; class base { public: void display() { cout<<"display function of base class"<<endl; } }; class derived:public base { public: void display() { cout<<"display function of derived class"<<endl; } }; int main() { derived d; //by default derived class display function will be called. d.display(); //inorder to invoke base class display function can call it as below //d.base::display(); return(0); }
Output:
display function of derived class