gabyk00
gabyk00

Reputation: 151

Calling an overridden method in a derived class

Let's suppose we have 3 classes: Person, Student and Worker. Student and Worker both are derived from Person. I want to make an array of persons, which consists of randomly position Student and Worker instances. There is a method called show() overloaded in both Student and Worker and I want to call that function instead of the Person show() method. I know how to do by casting the Person object like (Student*) or (Worker*) how could I use that method in array? Below is some sample code;

class Person:

Person::Person() {    
    this->name = new std::string("Gabi");
    this->age = 12;
}

void Person::show() {   
    std::cout << "Hi my name is " << *(this->name) << std::endl;
    std::cout << "and I am " << this->age << " years old" << std::endl;
}

class Student:

Student::Student() { 
    this->school = new std::string("ghica");
}

void Student::show() {

    Person::show();
    std::cout << "My school is " << *(this->school) << std::endl;
}

class Worker:

Worker::Worker() {
    this->workplace = new std::string("google");
}

void Worker::show() { 
    Person::show();
    std::cout << "My workplace is " << *(this->workplace) << std::endl;
}

If I call the show() method this way:

Person * myperson = new Student("Andrei", 29, "ghica");
myperson->show();

the school message will not appear, but if I do this:

Person * myperson = new Student("Andrei", 29, "ghica");
((Student*)myperson)->show();

it does. Any ideas?

Upvotes: 1

Views: 123

Answers (2)

Loghorn
Loghorn

Reputation: 2807

Declare the show method in the Person class as virtual:

class Person
{
    ....
    virtual void show();
    ....
};

Also, even if unrelated to the question, it's often useless to place this-> in front of each member variable use; in addition, I see you are declaring name and school as pointer to string: in most of cases this is unnecessary and wrong because you are giving up value semantic.

Upvotes: 2

Marco A.
Marco A.

Reputation: 43662

Overriding a method isn't sufficient to have it called via a pointer/reference to the base class. You need to make it virtual:

class Person {
public:
  virtual void show() { // Virtual function
      std::cout << "person show";
  }
};

class Worker : public Person {
public:    
  void show() {
      std::cout << "Worker show";
  }
};

int main() {

    Person obj;
    Worker obj2;

    Person* array[2];
    array[0] = &obj;
    array[1] = &obj2;


    array[0]->show(); // Person
    array[1]->show(); // Worker

   return 0;
}

Example

Upvotes: 2

Related Questions