Casts

In this code-snipped
1
2
3
4
5
6
7
8
9
10
11
12
13
class B {
public:
   virtual void Test(){}
};
class D : public B {
void Test();
void print(std:: string st) {
std::cout<<st<<'\n;
};
void f(B* pb) {
   D* pd1 = dynamic_cast<D*>(pb);
   D* pd2 = static_cast<D*>(pb);
}  


1) If pb == 0, that means pb is a null_ptr then there won't be any issue with converting it to a pointer to either D or B, and for both the result will be alike, right?

2) The conversions are unlike if pb is a pointer to the class B, ie., the dynamic-cast returns zero (failure) while static-cast does the task carelessly, all bets are off. right?
Last edited on
1) If pb == 0, that means pb is a null_ptr then there won't be any issue with converting it to a pointer to either D or B, and for both the result will be alike, right?
Wrong.

Your example doesn't demonstrate why it's wrong because there are no members in class D. You're working with the special case where sizeof(B) == sizeof(D).

The layout in memory is the class B for B, and class B followed by class D for D.

2) The conversions are unlike if pb is a pointer to the class B, ie., the dynamic-cast returns zero (failure) while static-cast does the task carelessly, all bets are off. right?
Right.

dynamic_cast<> uses a runtime check called RTTI (runtime type identification), which takes time. So in cases where you know what type it should be, a static cast is often used, to improve performance.
One should also ask if the use of a cast is necessary: it may not be, because a pointer to derived is a valid pointer to base.

http://www.cplusplus.com/doc/tutorial/polymorphism/


cpptutorial wrote:
One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature.
Topic archived. No new replies allowed.