473,395 Members | 1,458 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Copy Constructor & assignment operator

Dear All,

Whats the difference between a copy constructor and assignment
operator. We can assign the values of member variables of one object to
another object of same type using both of them. Then where is the
difference?

Jul 23 '05 #1
10 10692
I guess they are just for the convenience that you could create the
objects in different ways. for example, suppose A is class with
constructor A(int) and A(const A)

A a1(5);
A a2(a1);
A a3 = a2; // you can always create a3 using A a3(a2)

but suppose you have already create a3 using A a3(10), then you want to
assign a1 or a2 to a3, you have to use assignment operator: a3 = a1

Jul 23 '05 #2
am*********@gmail.com wrote:
Dear All,

Whats the difference between a copy constructor and assignment
operator. We can assign the values of member variables of one object to
another object of same type using both of them. Then where is the
difference?


The copy constructor is used to initialize a new instance from an old
instance, and is called when passing variables by value into functions
or as return values out of functions.
The assignment operator is used to change an existing instance to have
the same values as the rvalue, which means that the instance has to be
destroyed and re-initialized if it has internal dynamic memory.

You should look for examples and gotchas if you're trying to implement
them, see what the default implementation does (provided by the
compiler) and also understand why these are sometimes made private.
--Paul
Jul 23 '05 #3
Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator. Can anyone
enlighten me on that?

Jul 23 '05 #4
am*********@gmail.com wrote:
Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator. Can anyone
enlighten me on that?


As with about anything else, it depends on what you are doing.
If you want to make a copy of an instance, the copy constructor does it
in one step instead of creating a default instance and then copying members.
Initializing an instance where it is declared with the equals operator
can be compiled to use the copy constructor, I think. It may depend on
the compiler.

class A; // defined elsewhere
void f()
{
A a1; // initialize an A with default constructor
A a2(a1); // construct a new A using a1's values
A a3; // construct a default A
a3 = a1; // then replace values. Potentially more expensive
// than using copy ctor.
A a4 = a1; // should resolve to using copy ctor, but I am not sure.

// ...
}

--Paul
Jul 23 '05 #5
am*********@gmail.com wrote:
Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator. Can anyone
enlighten me on that?


If you know the difference between them, you should know when to use each of
them. If you want to make a new object that is a copy of an existing one,
create it using the copy constructor. If you already have the object and
want to overwrite its contents to make it a copy of another object, use the
assignment operator.

Jul 23 '05 #6

am*********@gmail.com wrote:
Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator. Can anyone
enlighten me on that?


In general, and even though it may seem counterintuitive, you should
prefer construction over assignment, whenever a choice is available.

For example, consider the numberString variable in the following
routine:

void PrintOneThroughTen()
{
for (int i = 1; i < 11; i ++)
{
std::string numberString( std::atoi( i ));

std::cout << numberString << ", ";
}
}

and in this implementation:

void PrintOneThroughTen()
{
std::string numberString;

for (int i = 1; i < 11; i ++)
{
numberString = std::atoi( i );

std::cout << numberString << ", ";
}
}

The first implementation constructs numberString while the second
assigns it a value each time through the loop. Both examples are
correct, but the first one by using construction is the more efficient
implementation than the second one which uses assignment to ensure that
numberString has the intended value.

The explanation for this rule of thumb (construction instead of
assignment) is left as an assignment to the reader to provide. :)

Greg

Jul 23 '05 #7
class A; // defined elsewhere
void f()
{
A a1; // initialize an A with default constructor
A a2(a1); // construct a new A using a1's values
A a3; // construct a default A
a3 = a1; // then replace values. Potentially more expensive
// than using copy ctor.
A a4 = a1; // should resolve to using copy ctor, but I am not sure.
The above line is ALWAYS a copy construction, which is just a short hand
for:

A a5 = A(a1);

// ...
}

--Paul

Jul 23 '05 #8

<am*********@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
Dear All,

Whats the difference between a copy constructor and assignment
operator. We can assign the values of member variables of one object to
another object of same type using both of them. Then where is the
difference?


One creates an object (copy ctor) based on another's attributes and the
other essentially modifies an object.

as in:

int x(5);
x = 6;

The trick here is to recognize that you have the option and the ability to
define how the copy-creation or assignment occurs. This can be rather
important with complex types which manage their own allocations, for
example.

Jul 23 '05 #9
Me
> Whats the difference between a copy constructor and assignment
operator. We can assign the values of member variables of one object to
another object of same type using both of them. Then where is the
difference?


Constructors are for initializing memory. Copy constructors are for
intializing it to another value of the same type (ignoring cv
qualifications). Assignment operators are for assigning an initialized
variable to another value. For example:

A foo;
A boo(foo); // copy ctor
A goo = A(foo);
// create temporary using a copy ctor, copy construct
// temporary into goo. Most compilers can elide this
// temporary due to RVO.
A moo = boo;
// same as A moo(boo); not A moo = A(boo); because
// boo is the same type as moo.
boo = foo; // assignment operator
boo.~A(); // destructor
// boo = foo;
// error: don't use assignment operator since boo is
// destroyed now
::new ((void*)&boo) A(foo);
// ok: copy constructs using placement new
// ::new ((void*)&boo) A(foo);
// error: don't construct an already initialized variable

Jul 23 '05 #10
<am*********@gmail.com> schrieb im Newsbeitrag
news:11**********************@f14g2000cwb.googlegr oups.com...
Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator.


You should never "use" them. The compiler needs them to do its work. All you
have to do is implementing both of them (and a d'tor) if any one of them
must do something the compiler-generated versions wouldn't do.

HTH
Heinz
Jul 23 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: away | last post by:
1. When a class defined with a member of pointer type, it's necessary to have a copy constructor and assignment operator. If don't pass objects of such class as value in a function and don't do...
10
by: utab | last post by:
Dear all, So passing and returning a class object is the time when to include the definition of the copy constructor into the class definition. But if we don't call by value or return by value, ...
8
by: rKrishna | last post by:
I was trying to understand the real need for copy constructors. From literature, the main reason for redfinition of copy constructor in a program is to allow deep copying; meaning ability to make...
13
by: blangela | last post by:
I have decided (see earlier post) to paste my Word doc here so that it will be simpler for people to provide feedback (by directly inserting their comments in the post). I will post it in 3 parts...
1
by: blangela | last post by:
3.0 Advanced Topic Addendum There are a few cases where the C++ compiler cannot provide an overloaded assignment operator for your class. If your class contains a const member or/and a...
2
by: Henrik Goldman | last post by:
Hi, Lets say you have class A which holds all data types as private members. Class B then inherits from A and does *only* include a set of public functions which uses A's existing functions for...
22
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float...
13
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help...
9
by: puzzlecracker | last post by:
From my understanding, if you declare any sort of constructors, (excluding copy ctor), the default will not be included by default. Is this correct? class Foo{ public: Foo(int); // no...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.