1

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

digitaltos
  • 85
  • 7

2 Answers2

4

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.

Community
  • 1
  • 1
dlf
  • 9,045
  • 4
  • 32
  • 58
  • Thank you, this piece of information saved me a lot of time and going to make my program more elegant. Thank you again. – digitaltos May 14 '14 at 19:02
  • If this is obvious to you I apologize, but if you're switching to pointers, make sure something is keeping the pointed-to objects alive, or you'll end up with an even bigger problem. – dlf May 14 '14 at 19:03
  • Yes, of course, that was not a problem. Now I'm stuck with that I need to get the type of an element in the vector. So to find something that will return a char* "Employee". – digitaltos May 14 '14 at 19:40
  • That's another subject, but you can use `dynamic_cast`. But even better is to design so it's not necessary. Here's a link to another question that discusses that subject a bit: http://stackoverflow.com/q/23569140/3549027 – dlf May 14 '14 at 20:22
  • Actually I have to get something to save to a file, but I think I just create an char* `Employee::getType()` method. Thank you anyways. – digitaltos May 14 '14 at 20:33
3

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335