Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Cents cNancy = cMark; //cMark is existing object

Here Copy Constructor is called, not Assignment operator?

Can any one tell why?

Thanks
Posted
Comments
PIEBALDconsult 18-May-13 13:48pm    
Not without more information we can't.

Here assuming that Cents as a class, cNancy, cMark instances of Cents class.

Cents cNancy; // here default constructor will be called.
cNancy = cMark; // here assignment operator will be invoked.
Cents cNancy = cMark;// Here new object cNancy is created from cMark by
calling copy constructor.
 
Share this answer
 
v2
Comments
PIEBALDconsult 18-May-13 13:48pm    
Any evidence to back your claim?
Steve44 18-May-13 16:35pm    
This is an optimization designed into the C++ language, whenever an object exists before, the assignment operator is invoked, whenever an object is to be constructed, the CopyConstructor is invoked. This avoids the inefficiency of a DefaultConstruction followed by an assignment vs. a CopyConstructor which should be semantically equivalent anyway.
Take a look here:
http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/

Santhosh G_ 18-May-13 14:02pm    
Here i expected Cents is a class, cNancy is an instance of a Cents class.
When creating an instance of Cents cNancy with an existing instance cMark copy constructor will be called. Could you please explain the problem. Do I have to explain anything else.
Because that is a C++ rule.

C++
Cents cNancy = cMark;

is the same as
C++
Cents cNancy(cMark);


That is variable initialization: see, for instance, Herb Sutter's GotW #1 - Variable initialization[^].
 
Share this answer
 
There is a difference between assignment and initialization.

Initialization looks like this - int i = 10;
Assignment looks like this - int i; i = 10;

So the rule is simple - Assignment operator is used for assignment.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900