-1

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;
6
  • 2
    You aren't using the assignment operator in your code. But post a minimal reproducible example. Sep 11, 2016 at 14:23
  • What error do you get? Sep 11, 2016 at 14:29
  • error: not possible to convert int to Example. I am using the Visual C++ compiler by the way
    – Topper
    Sep 11, 2016 at 14:32
  • Despite what it looks like that is not an assignment, its an initialization, it calls the constructor, not the assignment operator.
    – Galik
    Sep 11, 2016 at 14:34
  • thanks, I tried Example x1; x1 = 10; and it worked. So does this mean, that if you assign the number directly with the declaration, than it will call the (copy) constructor instead the overloaded assignment operator?
    – Topper
    Sep 11, 2016 at 14:37

2 Answers 2

1

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.

1

The line

Example x1 = 10;

is identical with

Example x1(10);

or

Example x1 = Example(10);

It calls the constructor, instead of the assignment operator. Obviously it requires a constructor like:

Example(const int& n) : number(n) {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.