| | > | > > In statement:
| > > Circle c1=c2;
| > > Is the assignment operator= of Circle called?
| > Eventually.
| > The generated code will typically be identical
| > to that of the code below (a single copy-ctr call).
| > But the assignment operator must be accessible
| > when using this syntax, as the compiler may
| > interpret it as an initialization followed by
| > an assignment.
| >
| When you say "the compiler may interpret it as an initialization followed
by
| an assignment.", do you mean that if this could be an initalization only
to
| some compilers and initialization plus an assignment to others. The
| compiler I checked proved to me only initialization is triggerred, no
matter
| if an assignment operator provided or not.
Sorry, I got somewhat confused in my first reply, but
here's a more detailed and formal answer:
Here's an extract of what the standard says (8.5):
T x = a; is called copy-initialization
T x(a); is called direct-initialization
If direct-initialization is used,
or if a has type T (+/- const/volatile) or a base class of T,
then x is directly created using a copy-constructor call.
If copy-initialization is used and the types are somewhat different,
then a temporary T instance is first created, and a copy-constructor
is then called to perform a direct-initialization of x.
However, the intermediate temporary can be optimized-out by the
compiler (and most compilers I tried do so).
=> no, an assignment operator is never called. However, if the type
of a is different from the type of x, there is one major difference
between the two syntaxes: the copy constructor of T will have to be
*accessible* (e.g. public if called outside of the class members)
if the copy-initialization syntax is used.
That was it...
As a summary:
- if in your code example c2 was also of type Circle,
then the two variable initializations are fully equivalent,
and translated into a single constructor call.
- if c2 was not of the same type, then the Circle c1=c2 syntax
can be less efficient (may involve an intermediate copy), and
the copy-constructor needs to be accessible.
With my apologies for the confusion,
Ivan