Home > front end >  Unable to push an element of type child to a vector of type base using shared_ptr
Unable to push an element of type child to a vector of type base using shared_ptr

Time:02-14

Based on this answer, it appears the following code should work:

File Board.h:

std::vector<std::shared_ptr<Piece>> pawnRow;
for (int x = 0; x < 8; x  )
{
     pawnRow.push_back(std::make_shared<Pawn>());
}

For reference Pawn.h:

#include "Piece.h"

class Pawn : Piece
{};

Instead I'm getting: error: no matching function for call to 'std::vector<std::shared_ptr<Piece> >::push_back(std::shared_ptr<Pawn>)'

What am I missing here? My ultimate goal is to have a vector of "pieces" that I can call functions like possibleMoveLocations() that will call the overloaded function in the child class.

Using C 20, gcc version 11.2.0 (MSYS2), Windows 11

CodePudding user response:

As per @Barry's comment, I had to inherit Piece publicly like so:

#include "Piece.h"

class Pawn : public Piece
{};

The code compiled just fine thereafter!

  • Related