user9441223
user9441223

Reputation:

Passing an object by reference and storing it as a member variable

I can't figure out how to make "a" be the same object as "b".

Gamestate.h :

class GameState {
public: 
  void init(A& b);

protected:
  static A a;
}

Gamestate.cpp :

A GameState::a;

void GameState::init(A& b)
    {
        ???
    }

I could use pointers like this :

Gamestate.h :

class GameState {
public: 
  void init(A* b);

protected:
  static A* a;
}

Gamestate.cpp :

A* GameState::a;

void GameState::init(A* b)
        {
            a = b;
        }

But I would prefer a to be the same object and not a pointer to the object so that I don't have to dereference it when I want to access "a".

Upvotes: 1

Views: 2220

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Short answer: You can't. The simple reason is that GameState::a and the object passed by reference to GameState::init are distinct objects, they will never be the same.

Now, let's talk about ways to fix this in an "idiomatic C++" way:

Firstly, think about what GameState::init() means. It is a call on an instance of class GameState, which only writes to a static class property. Why doesn't it write to the instance's property? This smells a bit as if GameState::a was effectively a global variable, which inherits all its badness.

As a different approach, pass dependencies (like the parameter to init()) into the constructor (a.k.a. "Dependency Injection"). Then, you can initialize a reference to that parameter with the injected dependency:

class GameState {
    public:
    GameState(A& a): m_a(a) {}

    private:
    A& m_a;
};

Note that you must make sure that the A instance outlives the GameState instance. In some cases, where you have to dynamically allocate things and where you don't need them outside any more, passing ownership via a smart pointer (std::unique_ptr) is desirable, you can then replace the reference with such a smart pointer.

Upvotes: 4

Related Questions