C++ virtual function not called in subclass

二次信任 提交于 2019-12-04 04:21:54

You are unconditionally casting b to an A* using a C-style cast. The Compiler doesn't stop you from doing this; you said it's an A* so it's an A*. So it treats the memory it points to like an instance of A. Since a() is the first method listed in A's vtable and b() is the first method listed in B's vtable, when you call a() on an object that is really a B, you get b().

You're getting lucky that the object layout is similar. This is not guaranteed to be the case.

First, you shouldn't use C-style casts. You should use C++ casting operators which have more safety (though you can still shoot yourself in the foot, so read the docs carefully).

Second, you shouldn't rely on this sort of behavior, unless you use dynamic_cast<>.

Don't use a C-style cast when casting across a multiple inheritance tree. If you use dynamic_cast instead you get the expected result:

B* b = new C();
dynamic_cast<A*>(b)->a();

You are starting with a B* and casting it to A*. Since the two are unrelated, you're delving into the sphere of undefined behavior.

((A*) b) is an explicit c-style cast, which is allowed no matter what the types pointed to are. However, if you try to dereference this pointer, it will be either a runtime error or unpredictable behavior. This is an instance of the latter. The output you observed is by no means safe or guaranteed.

A and B are no related to each other by means of inheritance, which means that a pointer to B cannot be transformed into a pointer to A by means of either upcast or downcast.

Since A and B are two different bases of C, what you are trying to do here is called a cross-cast. The only cast in C++ language that can perform a cross-cast is dynamic_cast. This is what you have to use in this case in case you really need it (do you?)

B* b = new C(); 
A* a = dynamic_cast<A*>(b);
assert(a != NULL);
a->a();    

The following line is a reinterpret_cast, which points at the same memory but "pretends" it is a different kind of object:

((A*) b)->a();

What you really want is a dynamic_cast, which checks what kind of object b really is and adjust what location in memory to point to:

dynamic_cast<A*>(b)->a()

As jeffamaphone mentioned, the similar layout of the two classes is what causes the wrong function to be called.

There is almost never an occasion in C++ where using a C-style cast (or its C++ equivalent reinterpret_cast<>) is justified or required. Whenever you find yourself tempted to use one of the two, suspect your code and/or your design.

I think you have a subtle bug in casting from B* to A*, and the behaviour is undefined. Avoid using C-style casts and prefer the C++ casts - in this case dynamic_cast. Due to the way your compiler has laid out the storage for the data types and vtable entries, you've ended up finding the address of a different function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!