Search code examples
c++const-cast

Why can't I const_cast the return of the conversion operator?


I've got a conversion operator that returns a const pointer, and I need to const_cast it. However, that doesn't work, at least under MSVC8. The following code reproduces my problem:

class MyClass {
public:
    operator const int* () {
        return 0;
    }
};

int main() {
    MyClass obj;
    int* myPtr;
    // compiles
    const int* myConstPtr = obj;
    // compiles
    myPtr = const_cast<int*>(myConstPtr);
    // doesn't compile (C2440: 'const_cast' : cannot convert from 'MyClass' to 'int *')
    myPtr = const_cast<int*>(obj);
}

Why is that? It seems counter-intuitive. Thanks!


Solution

  • To make it work you have to do :

    myPtr = const_cast<int*>(static_cast<const int*>(obj));
    

    When you const_cast directly, the compiler look for the cast operator to int*.