Question

How it comes that operation like foo = int can be done by both foo(int) (conversion constructor) and foo::operator=(int) (overloaded assignment operator)? When one be called instead of other (maybe one is rudimentary)?

#include <iostream>

class foo
{    
  public:

    foo(){}

    foo(int r_value)
    {
      std::cout << "\nfoo::foo(int)\n";
    }

    void operator=(int r_value)
    {
      std::cout << "\nfoo::operator=(int)\n";
    }

};

int main()
{
  foo f;
  f = 57;
  return 0;
}

Code above makes operator=(int) to run when both exist and foo(int) if operator=(int) is commented (or opposite).

Was it helpful?

Solution

This is basic overload resolution. Both overloads are viable:

  1. Binding 57 to foo::operator=(int) (exact match)

  2. Implicitly converting 57 to foo via the converting constructor, and binding the temporary foo object to the implicitly defined foo::operator=(foo const &).

Since the latter requires more conversions than the former, it is a less-good match, and the former overload is chosen.

You can still achieve the second call by making it explicit:

f = foo(57);  // binds perfectly to foo::operator=(foo const &)

The full set of rules for overload resolution are rather long and involved, but in individual cases like this the answer is straight-forward. See 13.3 ([over.match]) for the full, gory details, though.

OTHER TIPS

There is a difference:

foo a = 10;

Calls foo::foo(int)

foo a;
a = 10;

Calls foo::operator=(int) in a

Both of the implementations are different. The first is a Constructor and the second is an assignment. The Use cases varies, and each of them would be called accordingly based on the use case.

Use Case

The Constructor is called foo::foo(int)

foo f = 57;

The Assignment is called foo::operator=(int)

foo f;
f = 57;

Note

Using assignment in the above use case and in your example has more overhead, as it called the default constructor along with the assignment.

For this statement

f = 57;

the compiler at first considers all functions operator =. There are two such functions: the explicitly defined by you and the copy assignment operator implicitly defined by the compiler. The first one is the best suitable function. So it is called.

If you will comment this assignment operator then the compiler has only one function operator =. It is the implicitly defined copy assignment operator. But it can not be applied directly. So the compiler seeks a way to convert supplied argument to type foo. And it can do this by calling the conversion construuctor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top