How do you use operator=()?

15 hours ago 3
ARTICLE AD BOX

As @3CEZQV commented, int & cannot bind to constant.

What compiler can do (and does) - it creates temporary derived object using provided constructor (derived(int)) and then uses automatically generated copy assignment operator (derived &operator=(derived const &)).

Your operator= should have the following signature: derived &operator=(int) or derived &operator=(int const &).

Please note as others commented - you usually DO NOT WANT operator= to be virtual.

Tomek's user avatar

1 Comment

@lostbits You can see this in action if you implement the copy assignment derived &operator=(derived const &).

2026-03-17T07:46:01.013Z+00:00

The problem is that the assignment operator you've provided for derived has a non-const lvalue reference parameter of type int& which can't bind to rvalues like 5.

But since you've also provided a converting ctor derived::derived(int), the argument 5 can be implicitly converted to an object of type derived using this converting ctor(hence the name). To avoid this, you can make this converting ctor explicit which will disable the implict conversion of 5 to a temporary derived object. When to make constructor explicit in C++ lists some scenarios like yours, where explicit can/should be used.


How can I fix this

Change the parameter of the assignment operator such that it can bind to rvalues. So, you can either change it to take const int& or int.

Also see When to make assignment operator virtual.

Richard's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article