The performance cost of virtual functions means that when a class has at least one virtual function, the compiler builds a table of virtual function pointers for that class. This table commonly called the vtable contains an entry for each virtual function in the class. A vptr exists as a variable within each object of the class in memory. A common vtable of a class is pointed by the vptr. A vptr exists as a hidden member of the object created. A vptr helps to initialize an object of a particular class with the help of its constructor.
Let's understand this with the help of an example:
#include <iostream.h>
#include <conio.h>
class River
{
public:
virtual void wave1()
{
};
virtual void wave2()
{
};
};
class S1: public River
{
public:
virtual void wave1() {};
};
class S2: public River
{
public:
virtual void wave2() {};
};
int main()
{
cout <<" wave 1" << endl; getch(); return 0; }
In the preceding code snippet, there are three classes. Therefore, the setting of 3 virtual tables for each of these classes (River, SI, S2) is done by the compiler. The creation and addition of the virtual pointer is also done by the compiler, as shown in the following code snippet:
#include <iostream.h>
#include <conio.h>
class River
{
public:
Functionpointer *_vptr;
virtual void wave1() {};
virtual void wave2() {};
};
class S1: public River
{
public:
virtual void wave1() {};
};
class S2: public River
{
public:
virtual void wave2() {};
getch();
};
The compiler sets the vptr in the similar way as that of virtual functions. It means a virtua pointer points to the virtual table of the particular class after creating an object. For example, when an object of the River class is created, the vptr point to the v-table for the River class with the help of the compiler.
Let's understand this with the help of an example:
#include <iostream.h>
#include <conio.h>
class River
{
public:
virtual void wave1()
{
};
virtual void wave2()
{
};
};
class S1: public River
{
public:
virtual void wave1() {};
};
class S2: public River
{
public:
virtual void wave2() {};
};
int main()
{
cout <<" wave 1" << endl; getch(); return 0; }
#include <conio.h>
class River
{
public:
Functionpointer *_vptr;
virtual void wave1() {};
virtual void wave2() {};
};
class S1: public River
{
public:
virtual void wave1() {};
};
class S2: public River
{
public:
virtual void wave2() {};
getch();
};
The compiler sets the vptr in the similar way as that of virtual functions. It means a virtua pointer points to the virtual table of the particular class after creating an object. For example, when an object of the River class is created, the vptr point to the v-table for the River class with the help of the compiler.
No comments:
Post a Comment