Redis1001 Redis1001 - 4 months ago 28
C++ Question

Pushing derived class to vector of base class in c++

I have the following code:

class Official {
explicit Official(int iRow, int iColumn, int iRankHolder, int** aiBoardHolder);

class General : public Official {
explicit General(int iRow, int iColumn, int iRankHolder, int** aiBoardHolder) : Official(iRow, iColumn, iRankHolder, aiBoardHolder) {};

class Map {
std::vector<Official> aoOfficialStack;

void generateOfficialObject();

void Map::generateOfficialObject() {
aoOfficialStack.push_back(General(1, 2, 3, aiBoardPosition));

Question is why am I getting this error after calling generateOfficalObject()?

Error C2664 'void std::vector>::push_back(const Official &)': cannot convert argument 1 from 'General' to 'Official &&' Project c:\users\user\desktop\project\project\board\board.cpp 12

Thank you very much!


Your example program compiles. Either your example is incomplete, or your compiler isn't standard compliant.

The program is well formed and has defined behaviour. The behaviour might not be what you expect however. Object slicing is an obscure language feature that beginners may find counterintuitive. It makes no sense to create an instance of General, if you're only going to use the Official sub object. Ask yourself: why not create an instance of Official in the first place?