Assignment Operator in C++

The assignment operator for a class is what allows you to use = to assign one instance to another.

The assignment operator is used to copy the values from one object to another already existing object
For example:
        MyClass c1, c2; 
        c1 = c2; // assigns c2 to c1

There are actually several different signatures that an
assignment operator can have:

(1) MyClass& operator=( const MyClass& rhs );
(2) MyClass& operator=( MyClass& rhs );
(3) MyClass& operator=( MyClass rhs );
(4) const MyClass& operator=( const MyClass& rhs );
(5) const MyClass& operator=( MyClass& rhs );
(6) const MyClass& operator=( MyClass rhs );
(7) MyClass operator=( const MyClass& rhs );
(8) MyClass operator=( MyClass& rhs );
(9) MyClass operator=( MyClass rhs );

First, you should understand that if you do not declare an assignment operator, the compiler gives you one implicitly. The implicit assignment operator does member-wise assignment of each data member from the source object.If you are having any dynamic memory allocation data,we have to provide assignment operator otherwise compiler will take care.

No comments:

Post a Comment