Prev: Assignment operator definition required in case of reference data member why?
Next: why should you use c++ in such project ?
From: Nick Hounsome on 15 May 2010 06:55 On 14 May, 16:51, "Daya S. Prasad" <mail....(a)gmail.com> wrote: > Consider a code: > > class B { }; > > class TestClass { > B &obj; > public: > TestClass(B &refObj) : obj(refObj) { > cout << "Called ... TestClass(B &refObj)\n"; > } > TestClass & operator=(TestClass const &) { > cout << "Called ... TestClass & operator=(TestClass const &)\n"; > return *this; > } > ~TestClass() { > cout << "Called ... ~TestClass()\n"; > } > > }; > > B b_obj; > TestClass obj1(b_obj), obj2(b_obj); > obj1 = obj2; > > Above posted code works perfectly until and unless we've defined > assignment operator. As soon as we remove overloaded assignment > operator it throws compilation error. > > error: non-static reference member 'B& TestClass::obj', can't use > default assignment operator > note: synthesized method 'TestClass& TestClass::operator=(const > TestClass&)' first required here > > Can anybody please tell me exactly what's the reason for compilation > error. As per my understanding this error comes due to B & > TestClass::obj but reference is also an object with different name and > B can use its default assignment operator for assignment. Overall > TestClass is perfectly assignable class without overloaded assignment > operator. Then why compilation error? and why it removes when simply > define overloaded assignment operator? It might help to realise that, the compiler effectively implements obj as B* const obj; So the default assignment would be trying to change an const object. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |