Search code examples
c++castingshared-ptr

How to fix: error: invalid conversion from 'const MyClass*' to 'MyClass*'


I am getting this compile error:

error: invalid conversion from 'const MyClass*' to 'MyClass*'

Here is the code:

std::tr1::shared_ptr<MyClass> myClassA;
const MyClass* myClassB;
myClassA = std::tr1::shared_ptr<MyClass>(myClassB); // error here

I think I understand the error, just don't know how to fix. I need myClassB to be a const so how to convert/copy classB to a shared_ptr?


Solution

  • You'll need a shared pointer to a const object:

    std::tr1::shared_ptr<const MyClass> myClassA;
                         ^^^^^