Ivan Prodanov
Ivan Prodanov

Reputation: 35532

How to call a function from parent class?

I want to call an inherited function of a superclass (parent class) in C++.
How is this possible?

class Patient{
protected:
  char* name;
public:
  void print() const;
}
class sickPatient: Patient{
  char* diagnose;
  void print() const;
}

void Patient:print() const
{
  cout << name;
}

void sickPatient::print() const
{
  inherited ??? // problem
  cout << diagnose;
}

Upvotes: 2

Views: 176

Answers (1)

Andrew
Andrew

Reputation: 24866

void sickPatient::print() const
{
    Patient::print();
    cout << diagnose;
}

And also in case you want polymorphic behavior you have to make print virtual in base class:

class Patient
{
    char* name;
    virtual void print() const;
}

In that case you can write:

Patient *p = new sickPatient();
p->print(); // sickPatient::print() will be called now.
// In your case (without virtual) it would be Patient::print()

Upvotes: 10

Related Questions