Sunday, August 2, 2009

Trying to programm an Employee database in C++ using Polymorphism and std::Vector could anyone help me plz ?

its an assignment and its very urgent,just cant work out how I can use std::vector as a container for 3 types of emplyees:"Manager,Engineer and researcher" which should be drived from Employee class.


The problem is I cant access any drived class method (e.g data.printstat() ) from a vector arrey data:





//std::vector.


vector%26lt;Employee%26gt; data;


//costructing a Manager //


Manager man (name , salary ,Exp);


data.push_back(man);


data[0].printstat();//%26lt;=======doesnt work!





I have made printstat() in Employee(which is base part) virtual.





why isnt working??!!!





could any one be kind enough and send me a suggested code??!!!





many thanx

Trying to programm an Employee database in C++ using Polymorphism and std::Vector could anyone help me plz ?
Because an std::vector make a copy of the instances you push into it. But your vector is of type employee, so each entry hold the space for the data needed by the base class only, everything coming from the derived class has no where to go, only the base class stuff is kept by the copy pushed into the vector. So whatever the employee type was before, the copy is an Employee, and only an Employee.





This is sometime called slicing an object.


The solution is simple, have your vector contains Employee pointers and not employee values. (you need to make sure that the employees are not destroyed while the vector hold their address thought)





Polymorphism work with pointers. You hold pointers to the base class that are in fact pointers to derived class and then when you call a virtual method on one of them, you call the appropriate derived class virtual method (if implemented of course) for the actual type of the object referred by the pointer.


No comments:

Post a Comment