[...] This function is expecting an object type "Class1" and this can be different from "Class2" and therefore the definition of this function could contain functions that can't be executed on the object type "Class2" |
No, because a Class2 is a Class1. Every operation which can be applied to a Class1 can also be applied to a Class2.
1. What is the purpose of dynamic_cast and when to use it in simple words? |
C++ defines "static" and "dynamic" type. Static type is the type known to the compiler. Dynamic type is the real type that is maybe referred to by a reference or pointer to a base class. In other words, given
Derived d; Base& b = d;
the static type of the expression
b
is
Base
, but the dynamic type is
Derived
.
dynamic_cast
allows you to retrieve the dynamic (or "real") type of an object through a base class reference or pointer.
Consider this abstract base class.
struct Base { virtual ~Base() = default; };
And these two derived classes which provide orthogonal functionality.
1 2
|
struct D0 { void foo() { std::cout << "foo\n"; } };
struct D1 { void bar() { std::cout << "bar\n"; } };
|
Given a collection of polymorphic references to Base, dynamic_cast (or RTTI in general) can be used to handle different derived classes specially, with no extra information about what any given pointer refers to:
1 2 3 4 5 6 7
|
D0 a; D1 b;
std::vector<Base*> v { &a, &b };
for (auto&& elt: v) {
if (auto p = dynamic_cast<D0*>(elt); p) p->foo();
if (auto p = dynamic_cast<D1*>(elt); p) p->bar();
// ... more derived classes follow
}
|
Live demo:
http://coliru.stacked-crooked.com/a/9ce2941439232368
2. What is the advantage of down-casting using the first example "without dynamic_cast" and the second? |
There is no advantage. The example only serves to illustrate that the functionality provided by RTTI can be duplicated without actually writing
dynamic_cast
anywhere. (You can keep track of the real type with an enumeration, for instance.)
Code that relies on dynamic type should be kept to a minimum. Exhaustive listings like which appear around uses of RTTI and dynamic cast are especially important to minimize.
You might find this thread interesting - it discusses a similar problem, namely, how to handle multiple distinct objects without a whole lot of extra boilerplate (it is complicated, though):
http://www.cplusplus.com/forum/beginner/217282/