In C++ programming language, Functions overriding is a process of declaring the functions of same name and signatures as in a parent classes and a child classes. Functions overriding is usually used in terms of inheritance, it is also used to produce polymorphic behavior.
When a member function of child class is overridden then its object cannot access the member function of a parent class but in C++, overridden member function of a parent class can be accessed by the use of a scope resolution operator.
For Example:-
#include<iostream> #include<conio.h> class Parent { protected: int n; public: Parent(int p) { n = p; } void show() { std::cout << "n = " << n << std::endl; } }; class Child : public Parent { private: char ch; public: Child(char c, int m) : Parent(m) { ch = c; } void show() { std::cout << "ch = " << ch << std::endl; } }; main() { Child obj('@', 100); obj.show(); getch(); }
Explanation:-
In the above example we have declared two classes, Parent class and a Child class. The parent class have one protected data member ‘n’ and a public function “Show()”, both of these will be inherited in a Child class. The Child class has his own one private data member ‘ch’ and the other inherited field ‘n’. As we know a child class inherits all the protected data members and a public functions of a parent class, therefore we declared a new function with a same name and same signatures as a parent class, this process is called function overriding. Now in a “Main Function” we will create an object of a child class and call its member function ‘Show()’. Because the function is overridden therefore the override function of child class will be executed. However if in some case you want to execute the function of a parent class then you can access it by using scope resolution operator.