Topper Topper - 2 months ago 19
C++ Question

Operator= Overload with different parameter in C++?

When I create an object of Example (class), I want to assign it a int value with the equal operator, just to see how operator overloading works.

But I can´t compile it with the following code:

class:

Example& Example::operator=(int number)
{
this->number = number;
return *this;
}


main:

Example x1 = 10;

Answer

Despite what it looks like that is not an assignment, its an initialization. It calls the constructor, not the assignment operator.

Try this:

Example x1; // initialize
x1 = 10; // assign

In your example it is looking for a constructor that takes an int as its parameter.

Comments