Question

So i have a class called Person

class Person{

   private:

   public:
      Person();

}

and 1 more class called Patient

class Patient : public Person{

    private:
       string text_;
    public:
       Patient();
       void setSomething(string text){ text_ = text; }
}

now i have created an array of 5 People like

Person *ppl[5];

and added 5 Patients in each key of the array like

ppl[0] = new Patient();
ppl[1] = new Patient();
ppl[2] = new Patient();
ppl[3] = new Patient();
ppl[4] = new Patient();

now i want to call the setSomething function from the Patient class like this

ppl[0]->setSomething("test text");

but i keep getting the following error:

class Person has no member named setSomething
Was it helpful?

Solution

You have an array of Person*. You can only call public methods of Person on elements of that array, even if they point to Patient objects. To be able to call Patient methods, you would first have to cast the Person* to a Patient*.

Person* person = new Patient;
person->setSomething("foo"); // ERROR!

Patient* patient = dynamic_cast<Patient*>(person);
if (patient)
{
  patient->setSomething("foo");
} else
{
  // Failed to cast. Pointee must not be a Patient
}

OTHER TIPS

The compiler doesn't know that the pointer points to a Patient object, so you have to explicitly tell the compiler that it is:

static_cast<Patient*>(ppl[0])->setSomething(...);

Either that, or make setSomething a virtual function in the base class.

A small note though: Using static_cast only works if you're certain that the pointer is a pointer to a Patient object. If there is a change it's not, then you have to use dynamic_cast instead, and check that the result is not nullptr.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top