Wednesday, August 8, 2007

Checking the presence of Virtual table in a class c++

The Last day when i am debugging one program , i saw the __vfptr symbol in VC++ . This represents the the vtable of a class. When you debuging your program try obj1.__vfptr in watch window. It will show the virtual functions of that class.

On that time I thought about writing such a function to check the vtable presence in a class , it is not a bad Idea..

So This post is about checking the whether a class contains virtual function or not. I want to write a function like IsVTablePresent(MYclass) , the function will return true if there is a vtable ,Otherwise false.

I don't know is this type of functins are really useful or not , but i think these are really smart Smile.

 Here is my solution using templates , It is very easy.

template <typename T>
class tDervVir : public T
{
 virtual void VirtualFun(){} //dummy
};


template <typename T>
class tDervNormal : public T
{
 // No virtual functions inside.
};


template <typename T>
class VFinder                  
{
 public :
 int IsVirtualContains() //this is our function
 {


     tDervNormal<T> obj1;
     tDervVir<T>    obj2;
     return sizeof(obj1) == sizeof(obj2);
 }


};

By using the above classes it can be done. For example consider a class CSample as the class for testing.


class CSample
{
   virtual void PoorMan(){}
};



We can check CSample as the following way

VFinder<CSample> tester;
(tester.IsVirtualContains() ? cout << "Virtual present" : cout << "Virtual not present" ;


Thats all for now..

2 comments:

msnkd said...

Really nice . But no need for VFinder class. :)

msnkd said...

I like it verymuch, i am looking for something like this ..Thanks dude!!