c++ inheritance, vtable after casting
given the next simple example,
#include <iostream>
using namespace std;
class A {
public :
void print() {
cout<<"A print"<<endl;
}
};
class B : public A {
void virtual print() {
cout<<"B print"<<endl;
}
};
int main() {
A* aPointerB=new B();
aPointerB->print();
return 0;
}
the output is : A Print
from my understanding :
new B()
creates an object on the heap with a virtual table that contains one method and that's B::print(); i h开发者_开发问答ave two ideas to why this is happening,
- when casting the pointer to A is the virtual table entry for B::print() removed.
- in runtime the program doesn't check the vtable entry for print() because we are of type A and print() is not virtual in A, therefor it runs A::print().
which one is it ?
EDIT
it seems that my question wasn't clear, i know that A::print() is running because print() isn't virtual in A, my question is which of the 2 options is it for the reason print is running in A understanding the considering the way vtables and casting work.
thanks !
It happens because you didn't define print as virtual in A. That means that when calling on A objects, the lookup is not virtual.
A
's vtable doesn't contain any print
function, since it's not virtual. For this reason if you call print
on an object of type A
the vtable isn't checked, and A::print
(which is not virtual) gets called.
This means the code generated by the compiler just calls A::print
, without even accessing the vtable.
Between your two ideas the second is the right one; the first one makes no sense: vtables are never modified at runtime.
The print()
in A
needs to be declared as virtual
, not the one in B
as you have it.
精彩评论