How to declare and initialize reference to a data member?

Sometimes we may need to declare a data member which is a reference to another data member of the class  as shown below:

class A

{

public :

char *p ;

char *&rp ;

} ;

We can’t initialize a reference to a data member at the time of declaration. It should be initialized using ‘memberwise initialization as shown below.

#include <iostream.h>

class A

{

public :

char *p ;

char *&rp ;

A( ) : rp ( p )

{

p = “” ;

}

A ( char *s ) : rp ( p )

{

p = s ;

}

} ;

void main( )

{

A a ( “abcd” ) ;

cout << a.rp ;

}

It's very calm over here, why not leave a comment?

Leave a Reply




Feed Feed
Feed Feed