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:
#include <bits/stdc++.h>
using namespace std;
void aliasing( int N)
{
int & a = N;
cout << "Value of a: " << a << endl;
a = 100;
cout << "After Update:" << endl;
cout << "Value of a :" << a << endl;
cout << "Value of N :" << N << endl;
}
int main()
{
int N = 9;
aliasing(N);
return 0;
}
|
Output:
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:
#include <bits/stdc++.h>
using namespace std;
class gfg {
private :
int a;
public :
gfg( int a)
{
this ->a = a;
}
void setValue( int a)
{
this ->a = a;
}
int getValue()
{
return this ->a;
}
};
int main()
{
list<reference_wrapper<gfg> > l;
gfg obj(5);
l.push_back(obj);
cout << "Value of a for object obj is "
<< obj.getValue() << endl;
cout << "After Update" << endl;
obj.setValue(700);
cout << "Value of a for object obj is "
<< obj.getValue() << endl;
cout << "\nValue stored in the list is " ;
for (gfg i : l)
cout << i.getValue() << endl;
return 0;
}
|
Output:
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
Explanation:
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.
Last Updated :
12 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...