how to cast a const base class pointer into the derived class

  • A+

I am trying to cast a base class pointer into the derived class object. I can cast using old style but not with new style. I found some similar questions but don't find the answer.

Below is a downsized example of my problem. This line ((Scalar<int>*)base)->get(); gives me the correct result. This line static_cast<Scalar<int>*>(base)->get(); results in compiler error: error: static_cast from type 'const Base*' to type 'Scalar*' casts away qualifiers

class Base {     public:     Base() {};     virtual ~Base() {};     int getID() const { return 1; }; };   template<class T> class Scalar : public Base {     public:         Scalar() {};         ~Scalar() {};         void set(const T value)         {             m_value = value;         }         T get() const { return m_value; }     private:         T m_value; };   class Access { public:     const Base *find() const     {         return &m_scalar;     }      void example()     {         m_scalar.set(25);          const Base *base = find();          int res1 = ((Scalar<int>*)base)->get();         int res2 = static_cast<Scalar<int>*>(base)->get();           std::cout << res1 << std::endl;         std::cout << res2 << std::endl;      } private:     Scalar<int> m_scalar; }; 


When you do

int res1 = ((Scalar<int>*)base)->get(); 

you do what is called a c-style cast. This works because c-style casts don't do any checking and ignore the casting away of const. They just cast the source type to the destination regardless of any consequences.

On the other hand static_cast actually checks what you are doing and sees you are trying to cast the constness of base away. That isn't allowed by any cast except const_cast so you get an error. We could use that here to get rid of the constness but that isn't needed. What you can do is just cast to a const Scalar<int>* using

int res2 = static_cast<const Scalar<int>*>(base)->get(); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: