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
  •  | 
  •  

문제

(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.

도움이 되었습니까?

해결책

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.

다른 팁

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top