Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11098

Specific things with type cast operator

#include <iostream>
using namespace std;

struct A
{
    A(int a):a(a){}
    int a;
};

struct B
{
    operator A()
    {
        return 10;
    }
};

int main()
{
    B b;
    cout << ((A)b).a << endl;
    return 0;
}

This code compiles and prints 10 in visual studio. But in wikipedia next to cast operator I found this sentence: Note: for user-defined conversions, the return type implicitly and necessarily matches the operator name.

Now how the code above works? Is this feature of visual studio? Or it shoud match only implicitly?

Upvotes: 3

Views: 293

Answers (2)

John Dibling
John Dibling

Reputation: 101456

operator A() is a user-defined conversion operator. It's job is to return an A by-value when you cast a B to an A.

Your operator A() function is returning a literal integer value, 10. But operator A needs to return an A, so A's convert constructor is called with the value 10. This results in a temporary A being constructed. You are then accessing .a on this temporary object, and inserting the value of .a in to the stream, which results in you seeing 10 on the screen.

EDIT

When wiki said that the converstion operator "implicitly" returned an A, it meant that you don't have to specify the return type in the function declarion. It's always an A and there's nothing you can do about it.

When wiki said that it "necesarrily" returned an A it meant that it can't return anything but an A. It can't even return anything convertible to an A. It has to return an A exactly.

Upvotes: 6

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

B::operator A() implicitly returns an A. Therefore return 10 is implicitly equivalent to return (A)10, or return A(10).

Upvotes: 1

Related Questions