Is it possible to pass a reference to a reference?

In example:

A GameState object has a reference to a RenderWindow object;
GameState holds an object called Level, which ALSO holds a reference to a RenderWindow object. When constructing Level, can I pass the RenderWindow object reference from my GameState class?

Well that was a little confusing to explain, I hope you understand!
Last edited on
closed account (zb0S216C)
You can't pass a reference; only the referent.

Wazzak
So in this case I should use pointers?
It's not possible to have a reference to a reference. That would be totally useless because you can't modify a reference anyway.

You could let the Level constructor have a normal reference (to a RenderWindow object) as parameter.
Yes, that's what I meant...
A slightly ambiguous question?

As I understand it, there's any problem passing a reference to another reference. Of course, the very first reference has got to refer to something. As is:

1
2
3
int x = 0;
int& y  = x; // y is a reference to x
int& z = y; // z is another reference to x, init via y 


So the answer to:
can I pass the RenderWindow object reference from my GameState class?

Is yes, you can. The two references end up referring to the same actual original variable.

Where I assume you mean this kind of thing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <cstdio>

class RenderWindow {
private:
	std::ostream& m_os;
	RenderWindow& operator=(const RenderWindow&); // unused
public:
	RenderWindow(std::ostream& os) : m_os(os) {
	}
	void render(const char* msg) {
		m_os << msg << std::endl;
	}
};

class Level {
private:
	RenderWindow& m_rwnd;
	int m_id;
	Level& operator=(const Level&); // unused
public:
	Level(RenderWindow& rwnd, int id) : m_rwnd(rwnd), m_id(id) {
	}
	void report() {
		char msg[256] = "";
		sprintf(msg, "level id = %d", m_id);
		m_rwnd.render(msg);
	}
};

class GameState {
private:
	RenderWindow& m_rwnd;
	Level* m_pLevel;
	GameState& operator=(const GameState&); // unused
public:
	GameState(RenderWindow& rwnd) : m_rwnd(rwnd), m_pLevel(NULL) {
	}

	~GameState() {
		tearDown();
	}

	int init() {
		m_pLevel = new Level(m_rwnd, 42);
		return 0;
	}

	int tearDown() {
		if(NULL != m_pLevel) {
			delete m_pLevel;
			m_pLevel = NULL;
		}
		return 0;
	}

	int run() {
		m_rwnd.render("Hello world!");
		if(NULL == m_pLevel) {
			m_rwnd.render("<no level>");
		} else {
			m_pLevel->report();
		}
		return 0;
	}
};

int Run(RenderWindow& rwnd) {
	GameState gs(rwnd);
	int ret = gs.init();
	if(0 == ret) {
		ret = gs.run();
		gs.tearDown();
	}
	return ret;
}

int main() {
	int ret = 0;
	RenderWindow renderWindow(std::cout);
	RenderWindow& rwnd = renderWindow;
	ret = Run(rwnd);
	return ret;
}
Last edited on
Topic archived. No new replies allowed.