Re: operator= for a class with a const reference member
Gavin Deane wrote:
On 23 May, 16:19, 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"?
It's called the "assignment operator" and it doesn't construct
anything. Is that your misunderstanding?
MyClass& MyClass::operator= (const MyClass& mc)
{
m_ref = mc.m_ref ; //dosen't compile (obviously)
m_ref(mc.m_ref) ; //dosen't compile (obviously)
}
Your class definition for MyClass says that m_ref is const, i.e it
does not change throughout its entire lifetime.
Not exactly. 'm_ref' is a reference. It does not matter whether
it refers to a const object or to a mutable object. It still cannot
be changed to refer to some other object.
And yet you want to
MyClass to have an assignment operator, which means (conventionally),
"overwrite the existing value of the object with this new value". The
two are mutually exclusive. You need to resolve that contradiction in
your design. What does
m1 = m2;
actually *mean* to you when m1 and m2 are of type MyClass? Once you've
worked that out you can implement that meaning in your code. One
option is to change the definition of MyClass so that assignment
becomes possible. Or you might realise that assignment doesn't mean
anything for this type. A class doesn't *have* to be assignable if you
don't want it to be. If so, just remove the declaration of the
assignment operator from the class. With a const member, the compiler
will not be able to generate an assignment operator and any attempt to
assign will lead to a compiler error.
Most compilers will warn about inability to generate the assignment op
and in a good defelopment group setting warnings should be treated as
errors. In such situation it's better to declare the assignment op
private without trying to define it (or maybe define it, in fact, to
do something but leave the 'm_ref' alone).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask