Can I have a reference as a data member of a class? If yes, then how do
I initialise it?
Ans:
Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program.
Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.
Ans:
Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program.
#include
class sample {
private :
int& i ;
public :
sample ( int& ii ) : i ( ii )
{ }
void show( ) {
cout << i << endl ;
}
} ;
void main( ) {
int j = 10 ; sample s ( j ) ; s.show( ) ;
}
Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.
EmoticonEmoticon