Search code examples
c++polymorphismdestructormultiple-inheritancedynamic-cast

Dynamic cast in destructor


Is this code legal?

class Base1 {
};

class Base2 {
public:
    virtual ~Base2() {
        if (!dynamic_cast<Base1*>(this))
            std::cout << "aaaa" << std::endl;
    }
    Base2() {
    }
};

class MyClass: public Base1, public Base2 {
public:
    MyClass() {
    }
    virtual ~MyClass() {
        std::cout << "bbb" << std::endl;
    }
};

int main() {
    MyClass s;
    return 0;
}

I see both prints but I should see only one. I guess the dynamic cast is wrong. Is it possible to make a check of this kind?


Solution

  • Maybe I found the solution myself, the reply is no it's not possible:

    From bullet 6 of cppreference.com documentation:

    When dynamic_cast is used in a constructor or a destructor (directly or indirectly), and expression refers to the object that's currently under construction/destruction, the object is considered to be the most derived object. If new-type is not a pointer or reference to the constructor's/destructor's own class or one of its bases, the behavior is undefined.

    See also [class.cdtor]/6 of the standard.

    Since I'm casting to Base1 in Base2 destructor, this behavior is undefined.