I have a method in both the base class and the derived class. When I call this method on an object in the derived class it calls the base class method and not the derived class method. Here is my code:
Person.h
class Person
{
...
public:
...
virtual void coutPerson();
};
Person.cpp
void Person::coutPerson() {
cout << name << endl;
birthday.coutDate();
phoneNumber.coutPhoneNumber();
cout << city << ", " << state << endl;
}
Student.h
class Student : public Person
{
...
public:
...
virtual void coutPerson();
};
Student.cpp
void Student::coutPerson() {
cout << "DEBUG: Student::coutPerson()" << endl;
//Person::coutPerson();
cout << "Dorm Room: " << this->dorm << " " << this->dormRoom << endl;
}
Object created at: addPerson<Student>(personVector);
When object is created it is created as a Student because it calls the Student construtor.
Method called at: personVector[num-1].coutPerson();
The Student object is the one being told to coutPerson because it is displaying the info that I gave it when I created the Student object.
template<typename T> void addPerson(vector<Person> &personVector) {
T p;
personVector.push_back(p);
}
When the coutPerson() method is called on a Student object it only couts the name, birthday, phoneNumber, and city & state. What is wrong with this code? It should be calling the Student coutMethod…
Thanks!
Your
personVectorcontainsPersonobjects. Not references toPersonobjects, but actualPersonobjects. When you “put yourStudentobject into the vector”, what really happens is that the vector constructs a newPersonobject, which is copy-initialized with theStudentobject you give to it, that is, it creates a copy of thePersonpart of theStudentobject. This behaviour is also known as “slicing”.Since there is no
Studentobject in the vector, but only aPersonobject, it is no surprise that callingcoutPersonon it callsPerson::coutPerson, notStudent::coutPerson.If you want polymorphic behaviour, you have to store pointers (preferably smart pointers like
shared_ptrorunique_ptr) in the container. Note however that the objectpyou constructed in your function is destroyed on return, so for the object to survive (so you can have a pointer to it) you have to allocate it withnew.