Pregunta

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
¿Fue útil?

Solución

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
}

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top