C++ Class Copy Assignment

Introduction

We have used copy constructors to initialize one object with another object.

We can also copy the values to an object after it has been initialized/created.

We use a copy assignment for that.

Simply, when we initialize an object with another object using the = operator on the same line, then the copy operation uses the copy constructor:

MyClass copyfrom; 

MyClass copyto = copyfrom; // on the same line, uses a copy constructor 

When an object is created on one line and then assigned to in the next line, it then uses the copy assignment operator to copy the data from another object:

MyClass copyfrom; 

MyClass copyto; 
copyto = copyfrom; // uses a copy assignment operator 

A copy assignment operator is of the following signature:

MyClass& operator=(const MyClass& rhs) 

To define a user-defined copy assignment operator inside a class we use:

class MyClass 
{ 
public: 
    MyClass& operator=(const MyClass& rhs) 
    { 
        // implement the copy logic here 
        return *this; 
    } 
}; 

Notice that the overloaded = operators must return a dereferenced this pointer at the end.

To define a user-defined copy assignment operator outside the class, we use:

class MyClass //  www  .jav  a  2s . c o  m
{ 
public: 
    MyClass& operator=(const MyClass& rhs); 
}; 

MyClass& MyClass::operator=(const MyClass& rhs) 
{ 
    // implement the copy logic here 
    return *this; 
} 



PreviousNext

Related