Q:

How to call a parent class function from a derived class function in c++?

0

How to call a parent class function from a derived class function in c++?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

If a function is defined in a base class and it is not private then it is available in the derived class. You can call it in the derived class using the resolution operator (::). Let see a code where I am accessing the parent class function in the derived class as well as from the derived class object.

#include<iostream>
using namespace std;
class Base
{
public:
    virtual void print()
    {
        cout << "I am from base class" << endl;
    }
};
class Derived :public Base
{
    void display()
    {
        //calling base class function
        Base::print();
    }
};
int main()
{
    //derive class object
    Derived d;
    
    //calling print function
    d.print();
    
    //Calling print function of parent class
    // using derived class object
    d.Base::print();
    
    return 0;
}

Output:

I am from base class

I am from base class

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now