Q:

dynamic_cast understanding

I have recently started dynamic_cast and static_cast. I did kind-of understand what was happening in static_cast but not in dynamic_cast. The most I know is that static_cast can be used to convert data types and does not check on compile-time but dynamic_cast does. Also I have written the a code using dynamic cast but I am not sure how they are related.
Here is my code
#include <iostream>
using namespace std;

class Base{
public:
    virtual void setting(){
        cout << "Hello, I am a function from the base class" << endl;
    }
    virtual void say(){
        cout << "Base class says hi" << endl;
    }
};

class Child:public Base{
public:
    void setting(){
        cout << "Hello, I am a function from the child class" << endl;
    }
    void say(){
        cout << "Child class says hi" << endl;
    }
};

class Child2:public Base{
public:
    void setting(){
        cout << "Hello, I am a function from the child2 class" << endl;
    }
    void say(){
        cout << "Child class says Wazuppppp" << endl;
    }
};
void start(Base* bp){ //here is where I get confused
    Child* it_is_Child= dynamic_cast<Child*>(bp);
    if(it_is_Child){
        it_is_Child->say();
        it_is_Child->setting();
    }
    Child2* it_is_child2= dynamic_cast<Child2*>(bp);
    if(it_is_child2){ //then
        it_is_child2->say();
        it_is_child2->setting();
    }
};

int main(){
    Child cp1;
    Child2 cp2;
    start(&cp2);
    cout << endl;
    start(&cp1);
    system("pause");

    return 0;
 }

The confusion is that how are Child cp1 and Child2 cp2 are related to start function and how do they work. Also how does the compiler decides which one to pick.

A:

static_cast will generate an error during compilation, if the associated classes are not related (where one is inherited from the other, or both are inherited from a common ancestor).
dynamic_cast will return a null pointer during runtime, if the conversion-class is not the exact class of the converted object.
In order for dynamic_cast to work, the conversion-class must declare at least one virtual function. This is because dynamic_cast uses the V-Table pointer of the converted object, and an object has a V-Table pointer only when its class declares virtual functions.
For example, the behind the scene of Child* it_is_Child = dynamic_cast<Child*>(bp) is:
if (bp->__vfptr == Child::vftable)
    return (Child*)bp;
return nullptr;

Please note that on some compilers you also need to enable RTTI in the project settings.

