What is Function overriding in c++?
In C++ inheritance allows users to derive one or more classes from a class inheriting characteristics and member functions of its parent class. If both parent and child classes have function/s with same name and arguments (i.e. same type and equal number). This is function overriding in c++. It uses the concept of rewriting the base class function in child class. Below example can help you understand the concept. sometimes it is referred as method overriding in c++.
Example program: –
#include "stdafx.h" #include "iostream" #include"string" using namespace std; class person { protected: string name; string address; public: person() { name = ""; address = ""; } public: void getData() { cout << "Please Enter Name : "; getline(cin, name); cout << "Please Enter Address : "; getline(cin, address); } void show() { cout << "Name : " << name << endl; cout << "Address : " << address << endl; } }; class student :public person { string regNo; float cgpa; public: void getData() { cout << "Please Enter Registration Number : "; getline(cin, regNo); cout << "Please Enter cgpa : "; cin >> cgpa; } void show() { cout << "Registration Number : " << regNo << endl; cout << "CGPA : " << cgpa << endl; } }; void main() { person p; p.getData(); p.show(); student s; s.getData(); s.show(); }
Output: –
As we can see in above code that both parent and child classes have getData and show functions. Object for each class calls to its own member function.
Method overriding in c++ Example
We can access parent class function inside child class overridden function as:
Example program: –
#include "stdafx.h" #include "iostream" #include"string" using namespace std; class person { protected: string name; string address; public: person() { name = ""; address = ""; } public: void getData() { cout << "Please Enter Name : "; getline(cin, name); cout << "Please Enter Address : "; getline(cin, address); } void show() { cout << "Name : " << name << endl; cout << "Address : " << address << endl; } }; class student :public person { string regNo; float cgpa; public: void getData() { person::getData(); cout << "Please Enter Registration Number : "; getline(cin, regNo); cout << "Please Enter cgpa : "; cin >> } void show() { person::show(); cout << "Registration Number : " << regNo << endl; cout << "CGPA : " << cgpa << endl; } }; void main() { student s; s.getData(); s.show(); }
Note: – Function overriding is different from function overloading.
One thought on “Function Overriding in C++”