Kasair
Kasair

Reputation: 11

Calling a method of a derived class in vector of superior class

I have an vector of superior type class

vector<Parent> parents;

then i'm adding a derived class types let's say daughter and son

Son tempSon;
tempSon.setAge(7);
tempSon.setName("John");
parents.push_back(tempSon);
Daughter tempDaughter;
tempDaughter.setAge(9);
tempDaughter.setName("Emily");
parents.push_back(tempDaughter);

Now what the problem is when i iterate through the vector and call methods like

parents.at(0).printName();

The parent method gets called which does nothing and I want to call a child method. Another thing is that i do not know the type of the object passed(e.g whether son or daughter) so i can't cast it. I tried to use typeid(object) and it prints the parent class name instead of child class. Any ideas?

Upvotes: 0

Views: 99

Answers (2)

senfen
senfen

Reputation: 907

Are your classes have declared function as virtual? If no, there will be no polymorphic behavior.

//Yes, and vector of pointer to class.

Upvotes: 0

Drewen
Drewen

Reputation: 2936

To do that you should store POINTERS in the vector, instead of a copy of the object, becuase only the PARENT part will be stored.

Once you store the pointer, you can cast to the child class and call the correct method, or simply, make the method virtual in the parent class and call it without casting.

Upvotes: 2

Related Questions