Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function from parent class?

Tags:

c++

function

oop

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;
}
like image 939
Ivan Prodanov Avatar asked Nov 29 '25 04:11

Ivan Prodanov


1 Answers

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()
like image 194
Andrew Avatar answered Dec 01 '25 19:12

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!