vendredi 22 octobre 2021

Why can you dynamic cast an object to one that is of a completely different type? [duplicate]

I made 3 classes, base class A, with child classes B:A, C:A. I do the following and nothing breaks -- c->hello() prints "B". Why does this happen? Shouldn't it return a NULL pointer?

#include <iostream>
using namespace std;

class A {
  public:
  void hello() {
    cout<<"A"<<endl;
  }
  virtual ~A() = default;
};

class B : public A {
public:
  void hello() {
    cout<<"B"<<endl;
  }  
};

class C : public A {
public:
  virtual void hello() {
    cout<<"C"<<endl;
  }  
};

int main()
{
  A* c = new C();
  B* c2 = dynamic_cast<B*>(c);
  c2->hello();
}

Aucun commentaire:

Enregistrer un commentaire