views:

242

answers:

3

I'm trying to overload the dereference operator, but compiling the following code results in the error 'initializing' : cannot convert from 'X' to 'int':

struct X {
    void f() {}
    int operator*() const { return 5; }
};

int main()
{
    X* x = new X;
    int t = *x;
    delete x;
    return -898;
}

What am I doing wrong?

+9  A: 

You're dereferencing a pointer to X. Your class is OK (as far as it's implemented).

int main()
{
    X x; // no pointer
    int t = *x; // x acts like a pointer
}
Potatoswatter
+5  A: 

You should apply dereference operator to a class type. In your code x has a pointer type. Write the following:

int t = **x;

or

int t = x->operator*();
Kirill V. Lyadvinsky
+1  A: 

If you want the original code to work, you need to overload the int-cast operator for your class:

operator int() const { return 5; }
reko_t
`operator int` has a lot of gotchas and is best avoided. The dereference operator has legitimate use as pointer emulation.
Potatoswatter
@David: the ones that convert to `bool` have one more than the others, but maybe it's a drop in the bucket ;v)
Potatoswatter
@David: The question is about `int operator*`, not `operator int*`
visitor