Reference-typed Instance Variable in Class¶
TR;DR¶
Reference-typed instance variable must be initialized in the constructor using initializer list syntax!
Will never be reassigned
Later access/modification will only affect the variable bound to it rather than the reference itself
Overview¶
To be able to refer to an external object without copying it
It must be passed to the constructor of the class
Reference-typed instance variable must be initialized in the constructor using initializer list syntax
Example¶
1// ==== Reference type in class ====
2
3// Sharable configuration class
4class Config {
5 int value;
6 public:
7 Config(int value) : config(value) {} // constructor
8 int getValue() { return value; }
9};
10
11// ---- correct ----
12// Class that need to keep a reference to the configuration
13class MyClass {
14 Config &conf;
15 public:
16 explicit MyClass(Config &conf) : conf(conf) {}
17 // other methods can now use "conf" as if it's a Config object
18};
19
20// ---- Usage ----
21Config config(10);
22MyClass myClass(config); // so myClass.conf is bound to config
23
24// ---- wrong ----
25class MyClass {
26 Config &conf;
27 public:
28 explicit MyClass(Config &conf) {
29 this->conf = conf;
30 }
31};