I'm trying to create any iterable to store subclass objects in.
I currently am using a vector of pointers to the superclass, but this doesn't seem to allow any of the subclass-specific declarations to be used.
class piece
{
public:
int foo()
{
return 1;
}
};
class pawn : public piece
{
public:
int foo()
{
return 2;
}
};
std::vector<piece*> pieces;
pieces.push_back(new pawn());
pieces[0]->foo(); // returns 1 though pieces[0] should be a pawn
The call to pieces[0]->foo() returns 1, when I want it to return 2.
Debugging shows that the "new pawn()" creates a piece pointer, so I get why it doesn't use the pawn function, but I don't know why it isn't a pawn in the first place.
This is because your foo method is not virtual. In several other object-oriented languages, all methods are "virtual" by default, but they are not in C++. "Virtual" means that the function to be called is determined at runtime. When you have a non-virtual method, the compiler decides at compile-time which function to call based on static type information.
In this case, since you have a vector of piece, the compiler invariably determines that it should call pieces[0]->piece::foo(), without checking if there is a more refined version of it in a subclass. If you have a virtual method, the compiler determines that it should look into the object to figure out which one to call based on its type. You would to change the declaration of foo in piece and pawn:
virtual int foo() in piece;virtual int foo() override in pawn.See "Why do we need virtual functions in C++?". In the words of Kenneth Worden, "virtual allows the subclass method to be called, even if the object is being treated as its superclass".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With