Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_cast vs dynamic_cast

Tags:

c++

casting

Suppose I'm given a C++ library full of inheritance. I'm given a Base* in a function when I know that it is actually pointing to a Derived object and Derived inherits Base. But I don't know what kind of inheritance it is (public/protected/private). I also don't know if there is any virtual function in the hierarchy.

Given this situation, without looking into the source code/documentation of Base and Derived, which cast should I use? Or should I consult the code/documentation first to ensure about polymorphism?

Background

I am writing changeEvent function of QMainWindow in Qt 4.7. The changeEvent function takes QEvent* which I can cast to other type by knowing QEvent::type(). I was wondering if I should use static_cast or dynamic_cast.

Thanks.

like image 637
Donotalo Avatar asked Jan 10 '11 14:01

Donotalo


1 Answers

Use static_cast. If you know that your Base* points to a Derived, then use static_cast. dynamic_cast is useful for when it might point to a derived.

like image 180
Puppy Avatar answered Oct 10 '22 17:10

Puppy