Software & Finance





C++ - Assignment Operators





The syntax for assignment operator is given below:

The syntax is,

const MyClass& operator = (const MyClass &other)

There are two ways assignment operators gets called.
1. When the object gets assigned implicitly
2. When the object gets assigned explicitly.

 

Source Code


class MyClass

{

private:

    int m;

    int a;

    int b;

 

public:

    MyClass() : a(10), b(20), m(30)

    {

    };

 

    // Syntax for copy constructor

    MyClass(const MyClass &other)

    {

        this->a = other.a;

        this->b = other.b;

        this->m = other.m;

    }

 

    // Syntax for assignment operator

    const MyClass& operator = (const MyClass &other)

    {

        this->a = other.a;

        this->b = other.b;

        this->m = other.m;

        return *this;

    }

};

 

 

void main()

{

    MyClass a; // calls default constructor

    MyClass c; // calls default constructor

    MyClass b = a; // calls copy constructor

    c = b; // calls assignment operator

}