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.

2
  • 8
    These are not assignment operators - they're conversion operators. Commented Aug 12, 2014 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. If you want have custom copy-assignment then you have to overload the = operator (related reading: the rule of three). Commented Aug 12, 2014 at 11:33

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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)
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?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.