001 Function Overriding
001 Function Overriding
Function Overriding
• Function overriding in C++ is termed as the redefinition of base class
function in its derived class with the same signature i.e. return type and
parameters. It falls under the category of Runtime Polymorphism.
• It is a feature that allows to have a same function in child class which is
already present in the parent class.
• A child class inherits the data members and member functions of parent
class, but when you want to override a functionality in the child class then
you can use function overriding.
• It is like creating a new version of an old function, in the child class.
• To override a function, already declared in the base class, you must have
the same signature in child class.
Function overloading Vs overriding
Function Overriding
To call the Overridden function of
base/ derived classes by their
respective objects
Any shadowing/overriding?
Parent and child class Objects are
calling their respective functions.
Calling overridden function of Base class using the
base class Reference initialized with the address of
the child class Object
Any shadowing/overriding?
Parent and child class Objects are
calling their respective functions.
Function Overriding Analysis
• Since the overridden method disp() in the Derived class should shadow the disp()
method in the Base class.
• However, if we create a object/pointer of Base class type to point to an
object//address of Derived class and call the disp() function, it calls the disp()
function of the Base class.
• In other words, the member function of Base is not overridden.
• To avoid this, declare the disp() function of the Base class as virtual by using the
virtual keyword.
• If the virtual function is redefined in the derived class, the function in the derived
class is executed even if it is called using a pointer of the base class object
pointing to a derived class object. In such a case, the function is said to be
overridden.