How to use vtable to determine class type

I was recently interviewed for a position where C / C ++ is the main language, and for one question I was told that you can use vtable to determine which class in the hierarchy stores the base pointer.

So if you, for example, have

class A { public: A() {} virtual ~A() {} virtual void method1() {} }; class B : public A { public: B() {} virtual ~B() {} virtual void method1() {} }; 

and you instantiate A * pFoo = new B() , is it really possible to use vtable to determine if pFoo contains a pointer to an instance of A or B?

+7
c ++ vtable
source share
4 answers

This obviously depends on the implementation, but in most implementations, the representation of an object of class A or B in memory starts with a pointer to vtable. You can look at this vtable pointer, compare it with vtable pointers for objects that, as you know, have class A or B , and define the class of the object this way.

To illustrate (of course, this is nothing but a good style):

 A *pFoo=new B(); // pointer to object of unknown class (either A or B) A a; // Object known to be of class A B b; // Object known to be of class B void *vptrA=*((void **)&a); // Pointer to vtable of class A void *vptrB=*((void **)&b); // Pointer to vtable of class B void *vptrFoo=*((void **)pFoo); // Pointer to vtable of unknown object if(vptrFoo==vptrA) printf("Class A\n"); else printf("Class B\n"); 

Important: this is just an illustration of how most implementations work; in addition to being implementation dependent, this method breaks down when there is multiple inheritance. You should not do anything like this in production code; use RTTI instead.

+10
source share

Yes, it is quite possible - use dynamic_cast. This is a pretty crappy question - it might be a little better: "How is a dynamic implementation implemented?" but in fact, if you were asked either at the interview, I would have to ask the interviewer about him. Being a good or even excellent C ++ programmer, you do not depend on how you know how this happens, but these, of course, are simple questions for minor users.

+4
source share

Check the typeid () function.

+2
source share

You can access vpointer and even you can call any virtual method in the class via vpointer. But remember that it is EVIL.

Example:

 class A { public: void f1() { cout<<"bbb"<<endl;; } virtual void f2() { cout<<"ccc"<<endl;; } virtual void f3() { cout<<"ddd"<<endl;; } }; 

and call the main

 A a; typedef void (__thiscall* foo)(); (*(foo)((void**)(((void**)(&a))[0]))[1])(); 

It will call vpointer and then it will go by index and will execute the second method in vTable, which is f3 ().

Also pay attention to the use of RTTI, as already suggested.

+1
source share

All Articles