Benefits of copy constructor over assignment operator

A

Ajay

Hi all,
Can anybody please tell me that what exactly is the need of
copy constructor giving a real life example where i can not do things
with assgnment operator but can do things i want with copy constructor
only.Thanks in advance. ajay
 
M

Mark P

Ajay said:
Hi all,
Can anybody please tell me that what exactly is the need of
copy constructor giving a real life example where i can not do things
with assgnment operator but can do things i want with copy constructor
only.Thanks in advance. ajay

If you want to store your objects in standard containers (vector, list,
map, etc.) they need to be Assignable which in turn requires that they
have a copy constructor.

If you write all your code entirely from scratch then I suppose you can
simulate a copy ctor by constructing an object and immediately assigning
to it, but this doesn't seem very sensible.

Mark
 
M

Mike Wahler

Ajay said:
Hi all,
Can anybody please tell me that what exactly is the need of
copy constructor giving a real life example where i can not do things
with assgnment operator but can do things i want with copy constructor
only.Thanks in advance. ajay

class MyType
{
/* etc */
};

void foo(MyType arg)
{
}

int main()
{
MyType mt;
foo(mt); /* requires that 'MyType' has a
copy constructor */
return 0;
}

Depending upon the design of the 'MyType' type,
the needed copy constructor could be a compiler-
synthesized one (created if no user-defined
constructors are defined), or could need to be
a user-defined one (e.g. 'deep copy' needed).

Also, standard library containers require their
element types to be copyable as well as assignable.
'Copyable' means they must either be built-in
types, or have a (either default or user-defined)
copy constructor.

In my example above, with nothing else inside
the class definition, the compiler-generated
copy constructor will meet the requirement.

-Mike
 
R

Roland Pibinger

Hi all,
Can anybody please tell me that what exactly is the need of
copy constructor giving a real life example where i can not do things
with assgnment operator but can do things i want with copy constructor
only.Thanks in advance. ajay

A copy constructor, like any other constructor, creates an object from
scratch. An assignment operator (at least conceptually) destroys the
current contents of an object and replaces it with a copy of the
assigned contents. To answer your question, you cannot construct an
object with an assignment operator.

Best wishes,
Roland Pibinger
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top