Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
Mihran Hovsepyan Avatar asked Mar 09 '26 00:03

Mihran Hovsepyan


2 Answers

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.

like image 152
John Dibling Avatar answered Mar 10 '26 13:03

John Dibling


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

like image 21
Oliver Charlesworth Avatar answered Mar 10 '26 13:03

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!