Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert argument 1 from 'std::shared_ptr<ChaseState>' to 'std::shared_ptr<State<Cow>>

When trying to call a method setCurrentState Im getting the error:

StateMachine<Cow>::setCurrentState(std::shared_ptr<State<Cow>>)': cannot convert argument 1 from 'std::shared_ptr<ChaseState>' to 'std::shared_ptr<State<Cow>>'

This indicates that a std::shared_ptr<ChaseState> is not a std::shared_ptr<State<Cow>> but why is it not?

The call to the function:

std::shared_ptr<ChaseState> initialState = std::make_shared<ChaseState>();
m_stateMachine->setCurrentState(initialState);

State.h

#pragma once
template <class entity_type>
class State
{
public:
    virtual void enter(entity_type*) = 0;
    virtual void execute(entity_type*) = 0;
    virtual void exit(entity_type*) = 0;
};

ChaseState.h

class Cow;
class ChaseState : State<Cow>
{
public:
    ChaseState();

    // Inherited via State
    virtual void enter(Cow*) override;
    virtual void execute(Cow*) override;
    virtual void exit(Cow*) override;
};

In my StateMachine I have private variable:

std::shared_ptr<State<entity_type>> m_currentState;

and the setCurrentState function:

void setCurrentState(std::shared_ptr<State<entity_type>> s) { m_currentState = s; }

As I understand the derived class ChaseState is a State (behause it inherits from state).

like image 492
Sven van den Boogaart Avatar asked Aug 25 '26 16:08

Sven van den Boogaart


1 Answers

You need to declare your inheritance public. Class inheritance is private by default, meaning that you cannot cast from Derived to Base because the inheritance is not recognized outside of the class itself (same as how private members cannot be accessed outside the class).

To fix, make your inheritance public:

class ChaseState : public State<Cow>
//                 ^^^^^^
like image 134
Karl Nicoll Avatar answered Aug 27 '26 05:08

Karl Nicoll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!