sesodesa
sesodesa

Reputation: 1603

Dynamic cast from base to derived class in order to access a method

I have access to a base class PlayerBase, from which I have derived the class Player. There also exists another class, GameEventHandler, that is responsible for actually delegating "resources" to each player, with the mehtod GameEventhandler::ModifyResource:

bool GameEventHandler::modifyResource(std::shared_ptr<Course::PlayerBase> player,
                                      Course::BasicResource resource,
                                      int amount)
{

}

However, the implementation of this method has been left up to me, as you can see.

The problem is as follows: only the derived class Player has a method Player::increaseResource, that can increase one of its resources. However, the method modifyResource takes a shared pointer to a PlayerBase object as a parameter. This means, that in order to access the method Player::increaseResource, I would have to cast the Playerbase type pointer to a Player type pointer, or do some other trickery.

How does one handle this type of situation? I've tried something like

std::shared_ptr<Player> ownPlayerPtr
    = dynamic_cast<std::shared_ptr<Player>>(player);

but this gives the error std::shared_ptr<Player> is nmot a reference to a pointer. Changing this to

std::shared_ptr<Player> ownPlayerPtr
    = dynamic_cast<std::shared_ptr<Player>&>(player);

gives the error message 'std::shared_ptr<Course::PlayerBase>' is not polymorphic = dynamic_cast<std::shared_ptr<Player>&>(player);.

Any ideas as to why this is happening and what I would need to do to fix this?

Upvotes: 0

Views: 771

Answers (2)

Owl66
Owl66

Reputation: 185

You can use dynamic cast of shared pointer instead. If shared pointer is not empty, and such a cast would not return a null pointer, the returned object shares ownership over shared pointer's resources, increasing by one the use count. Otherwise, the returned object is an empty shared_ptr. i.e std::shared_ptr ownPlayerPtr = std::dynamic_pointer_cast(player).

Upvotes: 1

lucie
lucie

Reputation: 1010

Possible duplicate of this.

Try to use dynamic_pointer_cast:

std::shared_ptr<Course::Player> p = std::dynamic_pointer_cast<Course::Player>(player);

Upvotes: 1

Related Questions