简体   繁体   中英

How to correctly downcast a base class using dynamic cast in C++?

Let parent class A and a child class B be

// A.h
#include <iostream>
struct A {
    virtual void print() {
        std::cout << "A" << std::endl;
    }
};

and

#include <iostream>
#include "A.h"

struct B : public A {
    void print() override {
        std::cout << "B" << std::endl;
    }
};

Then in a program the following is possible:

int main() {

    A a1;
    a1.print();  // <-- "A"

    B b1;
    b1.print();  // <-- "B"
    
    A* a2 = new B();
    a2->print(); // <-- "B"
}

However, the following crashes:

B* b2 = dynamic_cast<B*>(new A());
b2->print(); // <-- Crashes

What is wrong here?

A does not derive from B (the reverse is true). You are creating an instance of A , not of B . Using dynamic_cast to cast an A object into a B* pointer will result in a null pointer, which you are not checking for before calling B::print() . Calling a non-static class method via a null pointer is undefined behavior , see: What will happen when I call a member function on a NULL object pointer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM