How to add reference of an object in Container Classes
We all are familiar with an alias in C++. An alias means another name for some entity. So, a reference variable is an alias that is another name for an existing variable/object etc.
Below is the program for adding reference to a variable:
Value of a: 9 After Update: Value of a :100 Value of N :100
Explanation: In the above program, a variable a is an alias of variable N that means we have given another name to variable N. So what ever we are doing with a it will effect N also and vice-versa.
Therefore, when we change the value of a to 100, then, value of N also changed to be 100.
Reference of an object in Container Classes:
The above method is correct to give an alias to any variable but in the case of containers the above method will throw a Compilation Error because containers directly can’t store the references, But there is an alternative way of doing the same. The template std::reference_wrapper in C++ STL is used to give reference to any containers in C++. The std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers(like in vector, list, etc) which cannot normally hold references.
Below is the program for adding a reference of an object in container class:
Value of a for object obj is 5 After Update Value of a for object obj is 700 Value stored in the list is 700
In the above program, when an object is created of class gfg, the constructor is called and the value of variable a is initialized to 5. We have stored the reference of the object in the list and then we have changed the value of the variable a to 700 by calling the member function setValue(). Now, when we see the value of the property a of the object whose reference we had stored in the list. The value stored is 700.