David G
David G

Reputation: 96790

Why do I get a compilation error upon specifying the return value of an overloaded type?

I understand that in C++ you can overload an operator like a function. And as common with functions in C++, you have to specify a return value:

struct A {

    int operator +();

};

Here I've overloaded operator+ as a function that returns an int. But I find that when I overload a type while giving it a return value, I get error: return type specified for 'operator int'.

struct A {

    void operator int() {} // error

};

But if I take away the return value it works fine.

struct A {

    operator int() {} // pass

};

Does the error mean that by my use of int before the function parameters, that I'm creating a function that returns an int. Or is this some mistake? What if I want the function to not return a value? Can someone please explain why I'm getting this error? Thanks.

Upvotes: 1

Views: 1614

Answers (4)

Walter
Walter

Reputation: 45414

you're confusing ordinary (unary and binary) operators with type-conversion operators

Upvotes: 1

Rost
Rost

Reputation: 9089

operator int() is implicit conversion operator from your type to int. So it could not have any return type except int which is defined by operator name.

Upvotes: 5

Pete Becker
Pete Becker

Reputation: 76245

By definition, operator int() returns an int. It will be called in contexts where an object of type A needs to be converted to int. That's quite different from the first code snippet, where the operator is operator+(); you can define it to return pretty much anything you like.

Upvotes: 8

Seg Fault
Seg Fault

Reputation: 1351

Well, operator int is the operator that turns your A into an int, therefore it already has the return type defined, and by writing void operator int you are giving it another return type!

Upvotes: 7

Related Questions