简体   繁体   中英

Why can I dynamic_cast to a non-virtual class?

Why does this compile, if A has no virtual functions?


class A {
    int a = 42;
};

class B {

    void* f() {
        return dynamic_cast<A*>(this);
    }

    virtual void my_virtual() {};
};

Note: Though it makes no sense to write something like this, this was the result of a refactor, after the base class was removed. I feel like there should have been a compiler error.

Because it's not a requirement, and it shouldn't be an error.

Consider the following addition to your classes (after making B::f() public):

class C: public A, public B
{
};

int main()
{
    C c;
    void* p = c.f();
}

which should, and does, return to p a pointer to the A subobject of c .

Only the conversion source is required to be of polymorphic type, and that is only if it is not known at compile time that the target is a base class of the source.
In the latter case, a decent compiler will not do any conversion at runtime.

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