Assigning Class Reference

Hi I am having reference variable in a class to avoid the
costly copy operation.

I am trying to assign this in costructor.
But the compiler is complaining with below error.

What is causing the Error????

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyClass
{
	AnotherClass& var;
	
	MyClass(); //As I Cant assign the Reference variable inside a 
                   // in defalut constructor

public:
	MyClass(AnotherClass &rhs)
	{
		this->var=rhs; //= operator is defined
	}
.........
.........
}


1
2
3
4
int main(){
   AnotherClass aClass;
   MyClass myClass(aClass);

1
2
3
Compiler Error:
     In constructor MyClass(AnotherClass &)  
     Unitialized reference member MyClass::var
Since a reference is bound made on construction of the object, you need to use an initializer list:

1
2
3
MyClass(AnotherClass &rhs) : var(rhs) //must use initializer list for constructor
{
}

@firedraco: Thanks I got it..
Topic archived. No new replies allowed.