Data member and member function overriding
If base class and derived class have same name of data members and same name of member functions then the process is called data member and member function overriding.
(same name of functions or data members give rise to override cases)
This means that if the base class and the derived class have the same name of data members and member functions, then derived class members=(data+fxn) hides or displaces or overrides the members of a base class.
We will write a program that has same functions name, and members name for base and derived class and show what problem occurs in output.
using namespace std;
cout<<"enter the value to n of a base class";
class Derived:public Base
cout<<"enter the value to n of a derived class";
cout<<"the value of both the n are"<<n+n;
D.input(); ///with the intention of calling the base class input
D.input();///with the intention of calling the derived class input
Its output comes as follows-:
enter the value to n of a derived class2
enter the value to n of a derived class 5
the value of both the n are 10
As shown in the code, the value of base class is overridden (not asked at all). The two values of latest derived classes are used (5+5=10), and this is the problem we want to solve using the concept of override.
Overridden members of a base class can be accessed by two ways-:
- By the help of a member function of a base class
- By the help of a derived class object
That will be discussed in the next blog post.