Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement conversion operator for pointer

Tags:

c++

operators

The question is simple but i can't find a solution.

class foo
{
public:
    operator int()
    {
        return 5;
    }
};

foo* a = new foo();   
int b = a;

Is it possible to implement that behavior?

like image 414
Mythli Avatar asked Jul 23 '11 20:07

Mythli


2 Answers

You can't. Conversion operators need to be members of a class, but foo* is not a user-defined class type, it's a pointer type (besides, int b = *a would work).

The best thing you can do is to use an utility function that does the casting.

like image 82
Alexander Gessler Avatar answered Sep 23 '22 00:09

Alexander Gessler


You can, by explicitly calling the operator:

foo* a = new foo();
int b = a->operator int();
like image 22
A. Lacombe Avatar answered Sep 26 '22 00:09

A. Lacombe