0

I have class that has assignment to string operator.

class turbo
    {
public:
    operator string   (void) {printf("assignment to string operator\n");return "bla2";}
    };

Assignment operation works just fine:

turbo t;
string s;
s=t;

And I have "assignment to string operator" in output.

Then I decided to make another assignment operator to turbo

class turbo
    {
public:
    operator string   (void) {printf("assignment to string operator\n");return "bla";}
    operator turbo   (void) {printf("assignment to turbo operator\n");return *this;}
    };

But code below does not calls turbo assignment operator.

turbo t;
turbo tt ;
tt=t;

Why?

I know that I can overload = operator, but I expect operator turbo work also since string one is operating.

Cœur
  • 37,241
  • 25
  • 195
  • 267
vico
  • 17,051
  • 45
  • 159
  • 315
  • 8
    These are not assignment operators - they're conversion operators. – Sander De Dycker Aug 12 '14 at 11:31
  • 4
    Like said in an above comment, the operators are *conversion* operators. And there's no use in converting a type to the same type, is there? Read more about [user-defined conversion operators here](http://en.cppreference.com/w/cpp/language/cast_operator). If you want have custom copy-assignment then you have to overload the `=` operator (related reading: [the rule of three](https://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29)). – Some programmer dude Aug 12 '14 at 11:33

2 Answers2

2

You are not overloading assignment operators, but conversion operators. So they are called when conversion takes place.

See c++: cast operator vs. assign operator vs. conversion constructor priority

Community
  • 1
  • 1
AlexD
  • 32,156
  • 3
  • 71
  • 65
  • Strictly speaking, they are _conversion_ operators, and are called when conversions take place (which might be due to casts, but can also happen implicitly without any cast) – Jonathan Wakely Aug 12 '14 at 11:33
1

The implicitly-declared copy assignment operator of a class takes a single parameter of type X const& (here turbo const&). Since your RHS operand is already of type turbo, there is no need to call the conversion function.

Indeed, a conversion function to the same type is never called implicitly; it can only be called explicitly (as turbo::operator turbo()) or possibly via a virtual conversion function in a base class. This is discussed in [class.conv.fct]:

1 - [...] A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void. [...]

See Under what circumstances would a type's conversion operator to itself be invoked?

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366