Home > Back-end >  Is it possible that we can call the parent's class method through a child class in main method?
Is it possible that we can call the parent's class method through a child class in main method?

Time:11-28

I have created a program in which there are two classes i.e., mother and daughter. Daughter class have inherited from mother class. Both classes has same method name but they print different data. Now in main method I have created an object of daughter class and called the display() through daughter's object and it is overriding mother's display() method.

Now I want to call mother's display() method in main method through daughter's object, So how can we do this? Is it possible to do this?

I have tried to do that but it is showing an Error (see that in last 3rd line of code)

#include <iostream>

using namespace std;

class mother{
    public:
    void display(){
        cout<<"Mother"<<endl;
    }
};
class daughter : public mother{
    public:
    void display(){
        cout<<"Daughter"<<endl;
    }
};

int main(){
    daughter rita;
    mother mother;
    rita.display();
    mother::rita.display(); //error
    return 0;
}

CodePudding user response:

You were very close.

rita.mother::display();

https://ideone.com/WZ7j8C

  •  Tags:  
  • c
  • Related