Kulamani
Kulamani

Reputation: 517

Why does assignment operator call both copy ctor and assignment operator?

Here is my code which I expect to output "Assignment" but getting both "copy" and "Assignment ".

#include <iostream>
using namespace std;

class Test
{
public:
    Test(){}
    Test(Test &t){ cout<<"\n copy ";}
    void operator = (Test t) {cout<<"\n Assignment ";}
};

void main()
{
Test t1;    //default ctor
Test t3;
t3=t1;    //Assignment 
}

If I change my code to

void operator = (Test &t) {cout<<"\n Assignment ";}

I get expected ouput only "Assignment".

What is the difference in both?

Upvotes: 1

Views: 71

Answers (3)

When you do following:

operator = (Test t)

compiler makes a copy of t1 to create t3....

you mean passing a reference of Test instead of a copy....

do

void operator = (Test& t) { cout << "\n Assignment "; }

instead of

void operator = (Test t) { cout << "\n Assignment "; }

Upvotes: 1

R Sahu
R Sahu

Reputation: 206667

void operator=(Test t) { ... }

Expects the argument by value. The argument t is constructed by using the copy constructor.

void operator=(Test& t) { ... }

expects the argument by reference. The reference is an alias to the object used to call the function. Hence, it does not create a new object.

Upvotes: 1

paddy
paddy

Reputation: 63481

The difference is that the argument Test t passes t by value. That invokes the copy constructor to create a separate local copy that you can use within the function.

When you use Test &t (note that it should have been const Test &t), you are passing a reference to the original value, thus avoiding copying.

Notes:

  • the correct signature of an assignment operator is this (satisfy the return value by return *this;):

    Test & operator = (const Test &t);
    
  • the correct signature for copy constructor is this:

    Test(const Test &t);
    

Upvotes: 4

Related Questions