1.

Can I Have A Reference As A Data Member Of A Class? If Yes, Then How Do I Initialise It?

Answer»

Answer :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.



Discussion

No Comment Found