How to call a base class function from a derived class function
Overview
In this shot, we'll learn how to call a base class function from a derived class function in C++.
Syntax
We can call a base class function from a derived class using the following syntax:
baseClassName :: functionName();
Syntax
Now, let's see some examples.
The base class
Let's first create a base class.
class base {public:void display () {cout << "Function of base class" << endl;}}
Explanation
- Line 1: We define a class
base. - Lines 3–5 : We create a function
display().
The derived class
Let's create a derived class by extending the base class.
class derived: public base {public:void display () {cout << "Function of derived class" << endl;// calling base class functionbase :: display();}}
Explanation
- Line 1: We define a class
derivedby extending the classbase. - Line 3–8: We override the
baseclass functiondisplay(). - Line 7: We call the
baseclass functiondisplay()from thederivedclass.
Example
#include <bits/stdc++.h>using namespace std;class base {public:void display () {cout << "Function of base class" << endl;}};class derived: public base {public:void display () {cout << "Function of derived class" << endl;// calling base class functionbase :: display();}};int main() {// create object of derived classderived d;d.display();return 0;}
Explanation
- Line 1: We import the
bits/stdc++.hlibrary. - Line 4–19: We create a
baseclass and aderivedclass. - Line 21–26: Inside the
main()function, we create an object of thederivedclass and call itsdisplay()function. - On calling the
display()function of thederivedclass:
- It prints "Function of derived class" on the console.
- It calls the
display()function of thebaseclass. - It prints "Function of base class" on the console.