William Barnes William Barnes - 3 months ago 17
C++ Question

c++ nested classes access

Following is a simplified header file detailing three Classes. I want to be able to keep the pointer in my "Game" class private, and allow Introduction to modify it. However, as is, this is not working. As Introduction is a derivative of GameState, I thought I would be able to modify this pointer? Examples had shown that this was possible. I don't really want to move this to the Public space within Game.

class Introduction;
class Game;
class GameState;

class GameState
{
public:

static Introduction intro;

virtual ~GameState();
virtual void handleinput(Game& game, int arbitary);
virtual void update(Game& game);

};


class Introduction : public GameState
{
public:

Introduction();

virtual void handleinput(Game& game, int arbitary);

virtual void update(Game& game);

};


class Game
{
public:

Game();

~Game();

virtual void handleinput(int arbitary);

virtual void update();

private:

GameState* state_;

};


The example I was following was here...http://gameprogrammingpatterns.com/state.html

EDIT: I am wanting to do something like this...

void Introduction::handleinput(Game& game, int arbitary)
{
if (arbitary == 1)
std::cout << "switching to playing state" << std::endl;
game.state_ = &GameState::play;
}


EDIT: Thank you for the responses, I think getters and setters are the way to go. And I apologise that the problem was not clear. The problem was that I did not understand the implementation I was trying to follow. I still don't understand it, but clearly there are ways to accomplish the same thing.

Answer

I see two possible solutions.

Using Friend class

You can declare friend classes in your Game class.

Something like:

class Game {
 public:
  // ...
 private:
  // ...
  friend class Introduction;
};

In this way, the class Introduction will be able to access to private member of Game class and modify it.


Getters And Setters

If you want to preserve data hiding principle, you can just provide a public member in order to modify the state of your game.

Here, an example:

class Game {
 public:
   void setNewState(GameState* setter) noexcept;
   const GameState* getCurrentState() const noexcept;
   // ...
};
Comments