I found in one article saying “static_cast is used for non-polymorphic type casting and dynamic_cast is used for polymorphic type casting”. I understand that int and double are not polymorphic types.
However, I also found that static_cast can be used between base class and derived class. What does polymorphic type here mean? Some people says polymorphic type means the base class with virtual function. Is that right? Is this the only situation? What else? Can anybody could elaborate this for me more?
First of all, the article is not completely correct. dynamic_cast checks the type of an object and may fail, static_cast does not check and largely requires the programmer to know what they’re doing (though it will issue compile errors for some egregious mistakes), but they may both be used in polymorphic situations. (dynamic_cast has the additional requirement that at least one of the involved types has a virtual method.)
Polymorphism in C++, in a nutshell, is using objects through a separately-defined interface. That interface is the base class, and it is almost always only useful to do this when it has virtual methods.
However, it’s rare-but-possible to have polymorphism without any virtual methods; often this is a sign of either bad design or having to meet external requirements, and because of that, there’s no way to give a good example that will fit here. (“You’ll know when to use it when you see it,” is, unfortunately, the best advice I can give you here.)
Polymorphism example:
Exercising the above classes slightly—also see my generic factory example:
It’s also possible to use polymorphism without inheritance, as it’s really a design technique or style. (I refuse to use the buzzword pattern here… :P)