Search code examples
c++pointersconstantsvirtual

error invalid conversion from 'const X*' to 'X*'


I have this piece of code:

class C
{
    virtual vec3 f1(const A* a, B* b){...}
    virtual vec3 f2(A const* a, B const* b)
    {
        vec3 color = f1(a, b);
        ...
    }
}

I want to call f1 from f2, but I don't know how to pass b in the correct way. Now on compiling, I get:

error: invalid conversion from 'const B*' to 'B* [-fpermissive]'

I've tried vec3 color = f1(a, const_cast<B *>(b));

This compiles, but then I get a segmentation fault on execution.

Please note that I can not change any function signature. I can also not change the definition of A or B to implement a getCopy() function for instance.

UPDATE:

I found a function that returns a modified copy of b, so my problem is solved. Thank you all for convincing me to stop trying to cast it directly into f1.


Solution

  • If you can't change the function signatures you can't solve your problem. Logically f2 is making a contract with the caller: "I will take a B* and use it, but I guarantee I won't modify the B it's pointing to". If you then pass that pointer to something else that does modify the B you have broken the contract. If f2 is intended to modify the B, the B* it takes shouldn't be const (and perhaps it should be a B&, as a side note).

    And as for the crash: Modifying an object originally declared as const is undefined behavior. Realistically this means the compiler is free to do something like store it in read only memory, and other tricky things. If you then try to write to it, all bets are off. It can crash. It can work. Anything can happen.