vico
vico

Reputation: 18171

Assignment operator overload

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.

Upvotes: 0

Views: 109

Answers (2)

AlexD
AlexD

Reputation: 32566

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

Upvotes: 2

ecatmur
ecatmur

Reputation: 157324

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?

Upvotes: 1

Related Questions