473,795 Members | 3,439 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copy constructors and overloading = What is the difference?

A book I have describes a class called vector.

It then explains (and I understand) the concept of a copy constructor,
which is needed to interpret statements like

vector b = a;
But then I get confused when it speaks of overloading =, and explains
that this concept is needed to interpret statements like b = a;
when b and a are vectors.
But didn't we take care of the b = a problem when we set up the
copy constructor?

Why on earth do we need to do the same thing twice (as it appears to
me)?

Apparently, we set up the copy constructor to allow copies of objects
in a class. But, for some unfathomable (to me) reason, this isn't
quite good enough and we need to overload the = operator (again in
order to allow copies of objects in a class.)

Could someone explain the difference between these two concepts, so
that I can see why both the copy constructor and the overloading are
needed?

Thank you,

Paul Epstein

Dec 7 '05 #1
7 1787
The copy constructor is most of all a constructor. This means that it
is called only if no instance is yet created. The code you gave:
vector b = a;


is equivalent to :

vector b(a);

As you can see this is another constructor that takes as parameter a
reference to an object of the same type.

The assignment operator on the other hand is needed when two instances
are already created but you want (at some point of the program
execution) the one to have the same value as the other. Example:

vector a;
vector b;
//....
a = b;

If you want to create a copy of an object it is not efficient to create
it with the default constructor and after that to call the overloaded
operator= . It is better to create a copy with the copy constructor.
But if you want to change a value of an object later in the program -
you cannot do this with the copy constructor because the object is
already constructed. So in this case you need the operator=;

Regards,
Irina Marudina

Dec 7 '05 #2
Irina Marudina <iz****@gmail.c om> wrote:
The copy constructor is most of all a constructor. This means that it
is called only if no instance is yet created. The code you gave:
vector b = a;


is equivalent to :

vector b(a);


The similarity in syntax between initialization in

vector b = a;

and assignment in

b = a;

is most likely what is causing the confusion. So, as Irina said,

vector b = a;

is really a copy constructor call, which is different from operator=.

--
Marcus Kwok
Dec 7 '05 #3
Copy constructor requires overloading of = operator in order to provide
a=b kind of interface, otherwise a=b will end up copying the address of
b to a not the deep copy of object.
If you do not overload = operator then a=b will in turn point to the
same object in memory. Which will end up creating inconsistency.
However if you overload = operator then a=b will create two different
copies of the object each pointed to by a and b. In that way you will
get an object 'a' which is exact copy of 'b' but 'b' will remain immune
to any modification made in 'a' and vice versa.

I hope this may clarify your doubt.

Dec 7 '05 #4
>> Copy constructor requires overloading of = operator in order to provide
a=b kind of interface, otherwise a=b will end up copying the address of
b to a not the deep copy of object.
Copy constructor does NOT require operator=! The "A a=b;" so called
"interface" is just a syntax sugar for
"A a(b);". If you don't believe me, try this:

-------------- Example start --------------
#include <iostream>
using std::cout;
using std::endl;

class A
{
private:
int m_i;
A& operator=(const A&); // forbid the compiler to generate operator=
for you

public:
A(int i = 0)
{
m_i = i;
}

A(const A& a)
{
m_i = a.m_i;
}

int get()
{
return m_i;
}
};

int main()
{
A a1(5);
A a2 = a1;

cout << a1.get() << ' ' << a2.get() << endl;

cout << &a1 << ' ' << &a2 << endl;

//a2 = a1; // Does not compile because there is no public operator=

return 0;
}
-------------- Example end --------------
If you do not overload = operator then a=b will in turn point to the
same object in memory. Which will end up creating inconsistency.
Check the addresses of the two objects and see for yourself if they are
the same when no operator= is present.
To be sure that the operator= is actually not present uncomment the
line "a2 = a1" and compile.
However if you overload = operator then a=b will create two different
copies of the object each pointed to by a and b. In that way you will
get an object 'a' which is exact copy of 'b' but 'b' will remain immune
to any modification made in 'a' and vice versa.
Operator= NEVER creates an object! It is just an operator (as its name
states), not a constructor. So it just assigns new values to the
members of an already created one.
I hope this may clarify your doubt.

Me too.

Regards,
Irina Marudina

Dec 7 '05 #5
From the holy Standard:

8.5/11: The form of initialization (using parenthesis or =) is generally
insignificant, but does matter when the entity being initialized has a
class type; see below. ...

8.5/12 The initialization .... is called /copy-initialization/ and is
equivalent to the form
T x = a;
The initializtion ... is called /direct-initialization/ and is
equivalent to the form
T x(a);

8.5/14 ... If the destination type is a (possibly cv-qualified) class type:
.... If the initiialization is direct-initialization, or if it is
copy-initialization, where the cv-unqualified version of the source type
is the same class as, or a derived class of, the class of the
destination, constructors are considered.

----

In other words

class A {
//....
};

A a;
A b = a; // calls copy constructor
Dec 7 '05 #6
pa**********@at t.net wrote:
A book I have describes a class called vector.

It then explains (and I understand) the concept of a copy constructor,
which is needed to interpret statements like

vector b = a;
But then I get confused when it speaks of overloading =, and explains
that this concept is needed to interpret statements like b = a;
when b and a are vectors.
But didn't we take care of the b = a problem when we set up the
copy constructor?

Why on earth do we need to do the same thing twice (as it appears to
me)?


When you see an declaration and initialisation like:
vector a;
vector b = a;

Then it's not an assignment, it's a construction:
vector b(a);

The syntax is just there for convenience, the following statements are
all initialisation:

// These two are semantically identical, the first form
// is "converted to" the second form
int a = 3;
int a(3);

// And again here
int b = a;
int b(a);

Hope that makes sense.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Dec 9 '05 #7

Irina Marudina wrote:
Copy constructor requires overloading of = operator in order to provide
a=b kind of interface, otherwise a=b will end up copying the address of
b to a not the deep copy of object.


Copy constructor does NOT require operator=() The "A a=b;" so called
"interface" is just a syntax sugar for
"A a(b);". If you don't believe me, try this:


Further to your example, a class that has a const member or a reference
member can (often) be copied but cannot be assigned.

Dec 9 '05 #8

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

Similar topics

9
14573
by: Stijn Goris | last post by:
hi all, Is it possible to declare 2 constructors in the same class? The constructors would have different number of parameters parameters... kind regards Stijn
22
2865
by: Shea Martin | last post by:
I have a String class (I know I am re-inventing the wheel, yes I have heard of boost, and of QString). My copy constructor does a deep (strcpy) of the char *_buffer member. I have a member function func(const String &param). When an actual String is passed as the param this is nice and efficient. I have a constructor which takes a const char* as an argument. And
42
5809
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
10
10721
by: ambar.shome | last post by:
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?
6
2390
by: Stephen Martinelli | last post by:
thanks for the help...just one more question.... can a class have more then two parameterized constructors?..i would like to be able to instanciate the class with a different number of argument..... thanks folks steve
3
1639
by: John | last post by:
Before anything else, thanks Marina, Workgroups and Ralf, for your help so far. I am now able to better define the question! After adding more console printout lines to CSum, I tried all permutations for constructors (none, default, two argument) and method call in body of constructor (none and one). Maybe this example is not representative, but for this example I found the following: 1. Without any constructors, the program works fine...
2
3549
by: nayannovellus | last post by:
As we know that both copy constructors and overloading = opeartor copies one object to another then whats the difference between copy constructor and overloading = operator. There must be some difference ... right?
1
2323
by: petschy | last post by:
hello, i've run into an error when qualifying a copy ctor 'explicit'. the strange thing is that i get a compiler error only if the class is a template and declare the variable as X<Zx = y. X<Zx(y) is fine. Tested with gcc 2.95, 3.3, 4.1, all gave the same error: t.cpp: In function 'int main()': t.cpp:44: error: no matching function for call to 'D<int>::D(D<int>&)'
22
3626
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);
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10437
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...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7538
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
6780
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
5437
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
4113
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
2
3723
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.