Hello All,
i have a small question regarding casts in C++.
1) Now, dynamic_casts ensure safety with casts. ie. for example: for the below polymorphic class:
class Base {
public:
virtual void foo() {}
};
class Derived : public Base {
};
int main()
{
Base *bPtr = new Base;
Derived *dPtr = dynamic_cast<Derived*>(bPtr);
return 0;
}
Now, dPtr would be NULL, thus we can ensure safety via some NULL checks. This is fine.
2) Now, for a non-polymorphic class, suppose i do:
class Base {
...
};
class Derived : public Base {
...
};
int main()
{
Base *bPtr = new Base;
Derived *dPtr = static_cast<Derived*>(bPtr);
return 0;
}
Now, there is no way to esure safety, and this is a potential unsafe operation.(if the pointer tries to access data from Derived)
Question:
In case of polymorphic classes, we have the safety provided by dynamic_cast. But, in the above non-polymorphic class, there is no safety.
I feel i am missing something here. Why is there no way in C++ to ensure the safety in this case?
Does it mean this above use case is flawed and that an inheritance heirarachy always needs an overriding behavior via virtual methods?
So, maybe i have some misconceptions about polymorphic behavior. Can someone please point out what i'm missing
Thanks!