I noticed that if I use C style casting (or reinterpret_cast) in the code below, I get a segmentation fault exception but if I use a dynamic_cast
, it is OK. Why is this? Since I'm sure that the pointer a is of type B because the Add
method already makes sure the input is of type B.
Do I have to use dynamic_cast
here even though I already guarantee that pointer a is of type B through my implementation?
Edit:
I do realize it's a bad practice in general to use C style casting (or reinterpret_cast). But for THIS particular case, why do they not work.
This has an application in practice because if class B is an interface and class D is forced to store type A pointer due to some reason. Dynamic cast is forced to be used here when the implementation already guarantees the type safety of the interface type.
#include <iostream>
using namespace std;
class A
{
public:
virtual ~A() = default;
};
class B
{
public:
virtual string F() = 0;
};
class C : public A, public B
{
public:
virtual ~C() = default;
virtual string F() { return "C";}
};
class D
{
public:
D() : a(nullptr) {}
void Add(B* b)
{
A* obj = dynamic_cast<A*>(b);
if(obj != nullptr)
a = obj;
}
B* Get()
{
return (B*)(a); // IF I USE DYNAMIC CAST HERE, IT'D BE OK
}
private:
A* a;
};
int main()
{
D d;
d.Add(new C());
B* b = d.Get();
if(b != nullptr)
cout << b->F();
}