473,624 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 10708
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*********@gma il.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*********@gma il.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*********@gma il.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*********@gma il.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 counterintuitiv e, you should
prefer construction over assignment, whenever a choice is available.

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

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

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

and in this implementation:

void PrintOneThrough Ten()
{
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*********@gm ail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.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

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

Similar topics

4
1803
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 assignment, should copy constructor and assignment operator be unnecessary? 2. If a base class have a pointer member, should its derived classes also need copy constructor and assignment operator, no matter if a derived class itself has a...
10
2552
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, we do not need to use the copy-constructor. So depending on the above reasoning I can avoid call by value and return by value for class objects, this bypasses the problem or it seems to me like that. Could any one give me some simple examples...
8
449
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 copies of classes with members with static or dynamic memory allocation. However to do this it requires the programmer to override the default copy constructor, the destructor & operator=. I wrote a small program to test if i can doa deep copy...
13
5003
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 to make it more manageable. Below is a draft of a document that I plan to give to my introductory C++ class. Please note that I have purposely left out any mention of safety issues in the ctors which could be resolved thru some combination...
1
2116
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 reference member, the compiler will not be able to synthesize an assignment operator for your class. It actually helps to think of a reference member as a const member (since it cannot be made to reference any other object once it has been initialized). ...
2
6244
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 manipulation. Now A has a copy constructor and assignment operator. What will happen if copying goes on in B? Do I need to have an overloaded set of functions which call the same copy functions that A has available? Or are they virtual in the...
22
3605
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 v);
13
3955
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 is much appreciated. JD
9
2887
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 Foo() is included, i believe. };
0
8240
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8625
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8482
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7168
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6111
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2610
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.