C++ Call Parent Method
This article will briefly discuss how to call a parent class function from a derived class function in C++.
Call Parent Class Function in C++
Calling a function in C++ is transferring the control to the function. Calling a function in C++ is not limited to only one specific way, and there are various ways to do it.
The first way is using the standard call operator()
, which will call any global, member, or static functions. The second way is using the dynamic cast operator, which only calls member functions related to the object’s class type.
The third way is using the static cast operator (static_cast
), which will only call global, static, or member functions. In this tutorial, we will specifically discuss how to call a parent function from a derived class.
In C++, a derived class can call the parent class function by using the parent::
keyword. For example, if you want to call the method print_message
from the parent class ParentClass
.
Syntax:
ParentClass::print_message()
- Create the function in the base class.
- Create the function in the derived class.
- Call the base class function from within the derived class function by appending the name of the base class, followed by two colons(
::
). For example,base_class::derived_class
.
Code Example:
#include <bits/stdc++.h>
using namespace std;
class parent {
public:
void demo() { cout << "x" << endl; }
};
class derived : public parent {
public:
void demo() {
cout << "y" << endl;
parent ::demo();
}
};
int main() {
derived zzm;
zzm.demo();
return 0;
}
Output:
y
x
In this code example, We created a parent class, a base class and a derived class.
After that, we created the demo()
function inside the main() function. When the derived class’s demo()
function is called.
Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.
Facebook