Raghav Sharma
Raghav Sharma

Reputation: 107

Initialisation, Copy constructor and assignment

I have a complex class and the main is something this:

int main()
{
complex c1;
complex c2=c1;
complex c3(c1);
complex c4;
c4=c1;
}

What constructors I would need in the complex class in order or all these statements to work? And, will the overloaded assignment or copy constructor be used in the following:

complex c2=c1;
complex c3(c1);

Upvotes: 1

Views: 78

Answers (3)

Laura Maftei
Laura Maftei

Reputation: 1863

Copy constructor is called when a new object is created from an existing object, as a copy of the existing object. And assignment operator is called when an already initialized object is assigned a new value from another existing object.

c4 = c1;  // calls assignment operator, same as "c4.operator=(c1);"
complex c2 = c1;  // calls copy constructor, same as "complex c2(c1);"

Upvotes: 1

Jan Fischer
Jan Fischer

Reputation: 71

A pretty good matching answer to your question and more information on the topic is given in: http://www.gotw.ca/gotw/001.htm or http://herbsutter.com/2013/05/09/gotw-1-solution

Upvotes: 1

ForEveR
ForEveR

Reputation: 55897

complex c1;

default c-tor.

complex c2=c1;

copy c-tor.

complex c3(c1);

copy c-tor.

complex c4;

default c-tor.

c4=c1;

assignment operator.

Default constructor is defined by compiler, if you have no other constructors defined (or you can define constructor without parameters).

Copy constructor and assignment operator are defined by compiler, if you don't define.

Upvotes: 3

Related Questions