I want to know what are static and dynamic type checking and the differences between them.
Static type checking means that type checking occurs at compile time. No type information is used at runtime in that case.
Dynamic type checking occurs when type information is used at runtime. C++ uses a mechanism called RTTI (runtime type information) to implement this. The most common example where RTTI is used is the dynamic_cast operator which allows downcasting of polymorphic types:
Furthermore, you can use the typeid operator to find out about the runtime type of objects. For example, you can use it to check whether the shape in the example is a circle or a rectangle. Here is some further information.
There are multiple types of casts available in C++.
The most common would be to use static_cast in order to cast a variable from one type of pointer to another. However, you can also use dynamic_cast, which will check to make sure (at runtime) that the pointers are of the correct type. With dynamic_cast, if the pointer is not of the right type, at runtime, it will return 0 instead.
The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception.
Make sure there is atleast one virtual function in Base class to make dynamicast work.
Assume you have:
For the static type, you look at how the variable is declared.
So the static type of
And the static type of
For the dynamic type, you look at what happens to be in the variable right now.
So the dynamic types of
Note that the dynamic type can change - if you did
Static type checking is type checking that is done at compile time. This is the only type of type checking that C++ does. Dynamic type checking is type checking done at run time. This is usually seen in dynamic interpreted languages, but is less common in compiled languages. Last I checked, C++ doesn't do any sort of dynamic type checking.
Edit: Apparently I'm out of date. See Reed's comment below.