T & T::operator = (const T & tval) { ... }
to return a reference but not o.k. for an overloaded plus operator
T & T::operator + (const T & tval) const { ... }
to return a reference.
The assignment operator can return a reference to its host class instance, which has a
scope larger than the scope of the assignment operator. It would, however, be
wrong for the plus operator to return a reference to its host class instance
because plus isn't allowed to change the host, and so would return the wrong
value. Plus can't return a reference to a T
class instance local to
itself because that class instance would dissapear when plus returned; it also
can't return a reference to a static local because it may need to use an
arbitrary number of static references (as in t1 + t2 + t3
).
The rule of three states that if a class needs any of a destructor, a copy constructor, or an assignment, it probably needs all three (or, if you prefer, if it needs a destructor, it also needs the other two). However, if you implement a copy constructor, then the compiler won't synthesize a default constructor, and you'll have to provide one of those too (assuming the class need it, which it usually does).
class A { B b; // and so one };
If B
doesn't appear anywhere else but in A
, then class B
doesn't
need a copy constructor.
Explain your answer.
False, for at least two reasons. First, a copy constructor does a bit-by-bit
copy only for those values that don't define a copy constructor. A class
always has a copy constructor defined, either implicitly or explicitly.
Second, if B
contains explicit dynamic memory, then it needs to implement
a copy constructor to properly handle the pointers.
this == &rhs
and *this == rhs
. Which is
better? Explain.
The first test is better because it's a pointer comparison, which is quick and
cheap, and it's correct, which the second test is not. The purpose of the
self-assignment check is to make sure two class instances aren't occuping the same
memory location. The second test checks to see if two class instances
represent the same value (assuming the class has defined operator ==()
),
which is not the same thing as occupying the same memory location. Two class
instances can have the same value but be in different memory locations.
This page last modified on 19 December 2001.