-1

Why can't one store an object as it's base virtual class ?

Consider the following example : It will segfault if Derived inherits virtually of Base

#include <iostream>
#include <memory>

class Base
{
public:
    virtual ~Base() = default;

    int baseInt = 42;
};

class Derived : public /* virtual */ Base  // <<< Uncomment the virtual to get a segfault
{
public:
    int derivedInt = 84;
};


int main()
{
    Base *base_ptr = new Derived();

    Derived *derived_ptr = reinterpret_cast<Derived *>(base_ptr);

    std::cout << "  baseInt is "    << derived_ptr->baseInt 
              << ", derivedInt is " << derived_ptr->derivedInt << std::endl; // segv on this line
}
Yanis.F
  • 612
  • 6
  • 18
  • You need to `static_cast`, not `reinterpret_cast`. – Botje Nov 22 '19 at 12:35
  • I get the following error with static_cast and c-style cast : `cannot convert from pointer to base class ‘Base’ to pointer to derived class ‘Derived’ because the base is virtual` – Yanis.F Nov 22 '19 at 12:37
  • Apologies, you need to even use `dynamic_cast`, as [this answer](https://stackoverflow.com/a/52245017/1548468) explains. – Botje Nov 22 '19 at 12:39
  • Does this answer your question? [diamond inheritance virtual member casting with pointers](https://stackoverflow.com/questions/52244794/diamond-inheritance-virtual-member-casting-with-pointers) – Botje Nov 22 '19 at 12:39
  • dynamic_cast gives me the following error `error: cannot dynamic_cast ‘base_ptr’ (of type ‘class Base*’) to type ‘class Derived*’ (source type is not polymorphic)` – Yanis.F Nov 22 '19 at 12:40
  • Add a virtual destructor to `Base` to make it polymorphic. – Botje Nov 22 '19 at 12:43
  • That works. I'm adding the virtual destructor to the question, do you mind writing your answer so I can accept it ? – Yanis.F Nov 22 '19 at 12:45

1 Answers1

2

The reinterpret_cast you used simply uses the Base pointer as if it were a Derived pointer.

Instead, this is one of the few situations where you should use a dynamic_cast. The example in the documentation for dynamic_cast shows such a downcast.

Botje
  • 26,269
  • 3
  • 31
  • 41