When I make a vector of a parent class, if I put a child there, child's members will be lost? [duplicate]

StackOverflow https://stackoverflow.com/questions/23662685

  •  22-07-2023
  •  | 
  •  

Question

(Sorry if this question was asked here before, but I searched for it for hours now, and couldn't find anything. Someone said that what I want is possible, and he told me how, I did as he said yet it is total failure.)

First of all, here is a class diagram for the easier presenting of the question.

Class diagram for my problem

Then the code which doesn't do what I want:

int main()
{
    Employee jack("Jack", 100);
    People guys(jack);             // using push_back 
...
}

So when this happens, as the debug mode shows, guys[0] will only have a name, no salary. Is it even possible, to an object in the vector to have other members than name? Or my only choice is to make an Employee vector?

Edit: Person is virtual by the way.

Was it helpful?

Solution

The vector needs to be of type vector<Person*> (or better yet, one of the smart pointer types like shared_ptr or unique_ptr) in order to do this. Otherwise, the Employee will be sliced into a Person when it is added, as you are seeing.

Vlad from Moscow's answer explains why this is the case.

OTHER TIPS

The polymorphism works with pointers and references to base classes. You may not define a vector of references but you may define a vector of pointers to a base class.

Relative to your example vector people should be defined as

std::vector<Person *> people;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top