Showing posts with label virtual table. Show all posts
Showing posts with label virtual table. Show all posts

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..

Wednesday, January 10, 2007

Virtual Function and ZeroMemory

What caused me to write this post is a BUG. Really i am not joking.. Everone know that there is a virtual table pointer is present at the beginning of the object memory . i am also know that.. But i did a mistake long ago . Following lines shows it...

class Base
{
public :
   virtual void Render()
   {
    }
};


class Derived: public Base
{
    // i have several data members here..
public :
    Derived()
    {
        // For easily initializing all of my data members to zero , i used ZeroMemory here
       ZeroMemory(this,sizeof(Derived));
       // Danger .. This also clear the virtual table pointer..
    }
    void Render()
   {
   }
};
So when i called it like
Derived *d = new Derived()
d->Render();

it crasheddd .... because of the ZeroMemory in the constructor set the vptr to Zero.