How to call a base class function from a derived class function in C++?

In this blog post,  you will learn how to call a base class function from a derived class function in C++. The primary prerequisite to solving this problem is an understanding of inheritance. So here I assumed you have already an understanding of inheritance in C++.

So let’s get started with the problem statement.

Problem statement:How to call a parent class function from a derived class using C++? For example, suppose I have a class called Base, and a class called Derived that is derived from the Base class. In both classes, there is a function name display(). Now the problem is how do I call the display() of the Base class within the display() of the child class?

class Base
{
public:
    void display()
    {

    }
};

class Derived:public Base
{
public:
    void display()
    {
        //Want to call here base class display()
    }
};

 

Solution:

In your case, display() is a public function, so if a function is defined in a base class and is not private then it is available in the derived class. You can call it in the derived class using the resolution operator (::).

Consider the below example code,

#include<iostream>
using namespace std;


class Base
{
public:
    virtual void display()
    {
        cout << "I am from base class" << endl;
    }
};


class Derived :public Base
{
    public:
    void display()
    {
        //calling base class function
        Base::display();
    }
};


int main()
{
    //derive class object
    Derived d;

    //calling display function
    d.display();

    //Calling display function of parent class
    // using derived class object
    d.Base::display();

    return 0;
}

Output:

I am from base class

I am from base class

 

Recommended Articles for you: