Questioning
Questioning

Reputation: 2043

C++ Polymorphism and Overriding

I'm having a hard time getting this working in C++, I've managed it in C# but I've not used C++ much so I'm not sure on the syntax.

The purpose of this is for a simple state manager, each state inherits from a base class called "state".

I've gotten overriding to work but I can't seem to manage the polymorphism aspect. That is that I cannot have an object "State currentState" and set that object to equal "menuState" and have it run the desired function, I know this is because it is only finding the signature for the State class but I am unsure how to avoid it. Here's some simplified code so that someone can help me understand.

// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

// State.h
class State{
public:
  virtual void drawState();
};

// State.cpp
void State::drawState() {
    cout << "Base state.\n";
}

// MenuState.h
class MenuState: public State {
public:
  virtual void drawState();
};


// MenuState.cpp
void MenuState::drawState() {
    cout << "Menu state.\n";
    State::drawState();
}

int main ()
{
    State currentState;
    MenuState menuState;

    currentState = menuState;
    currentState.drawState();

    system("pause");
    return 0;
}

If you change "State currentState" to create an object of MenuState the code will work as I require it to, however I need it to be the parent class so that I can set the current state to other states I will create in the future such as GameState.

Thank you.

Upvotes: 2

Views: 1485

Answers (2)

sampson-chen
sampson-chen

Reputation: 47367

Change your code to:

int main ()
{
    State *currentState;

    currentState = new MenuState();
    currentState->drawState();

    system("pause");
    delete(currentState)
    return 0;
}

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258648

Polymorphism doesn't work with plain objects because of slicing. You have to use references or (smart) pointers. In your case, pointers, as references can't be re-assigned:

int main ()
{
    State* currentState = NULL;
    MenuState menuState;

    currentState = &menuState;
    currentState->drawState(); //calls MenuState::drawState()

    NextState nextState; //fictional class
    currentState = &nextState;
    currentState->drawState(); //calls NextState::drawState()

    system("pause");
    return 0;
}

In your code:

State currentState;
MenuState menuState;

currentState = menuState;

the assignment slices menuState - it basically just copies the State part of it to currentState, losing all other type information.

Upvotes: 5

Related Questions