Advertisement



< Prev
Next >



C++ Function Overriding





In C++, when a class is inherited, you can override the definition of any of its existing accessible methods in its subclass by a feature known as function overriding. Hence in simple words, function overriding is overriding the definition of a superclass function in its subclass.

Besides other rules that we are going to explain for function overriding, one basic rule is that a superclass function being overridden must have the same name in the subclass as well.




Use of function overriding


The key benefit to function overriding is that you can alter the behaviour of the function inherited from a superclass and define it according to need of the subclass.





A simple example of function overriding.


//C++  Example of function overriding 


#include<iostream>

using namespace std;

class A				//superclass
{
public:

void name()			//function name() in class A 
{
	cout<< "A" << "\n";
}
};

class B : public A		//subclass of A
{
public:

void name() 			//function name() of class A is overridden in class B
{
	cout<< "B" << "\n";
}
};

int main()
{
	A ob;
	ob.name();	

	B ob1;
	ob1.name(); 		//call to overridden function name() in B class
}


Output


A
B


In this example, class A is inherited by class B. The name() function of class A is returning A, but when this function is inherited and overridden by class B, it is returning B.




Rules for function overriding -:








Why function overriding is needed?


Function overriding is mainly used in a situation when we want to create a more specialized version of a generic(general) function inherited from a superclass, within the subclass.



Please share this article -





< Prev
Next >
< Function Overloading
Constructors in C++ >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement