Click here to Skip to main content
15,888,968 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

In C++ , how VPointer is generated as per virtual function in base class or derived class or object we create in main.

Example:

C++
class Shape
{
public:
Shape(){}
~Shape(){}
virtual void Draw(){}
virtual void Draw1(){}

};

class Circle : public Shape
{
public:
Circle(){}
~Circle(){}
void Draw(){}

};

int main()
{
}

how many VPTR is created or generated ?
Posted
Comments
Andreas Gieriet 25-Jun-14 2:35am    
Why to bother? This is something behind the scene.
BTW: you should make the destructor of the base class virtual too, otherwise the derived destructor might not be called.
Cheers
Andi
PS: If it's a matter of object size, try sizeof(inst) to evaluate the effect.
ranjithkumar81 26-Jun-14 1:52am    
I need to understand , what is happening in behind scene

Is it an assignment on OOP theory? First of all, you need to understand when the virtual method table is generated and how are those tables mapped on the types and their members. You will be able to count those pointers (pointless business in practice, but might be a fair device to check up your understanding), if you learn how VMT (vtable) works. For example, after reading and understanding of this article:
http://en.wikipedia.org/wiki/Virtual_method_table[^].

Good luck,
—SA
 
Share this answer
 
v2
Comments
nv3 25-Jun-14 16:13pm    
Hello Sergey!

Why do you think that Circle::Draw() is an apparent mistake? As far as I can tell, it's a simple override of a virtual function (even if the virtual keyword is omitted in the derived class). Am I missing something here?
Sergey Alexandrovich Kryukov 25-Jun-14 17:22pm    
Ah, I forgot that this is the C++. :-)
Thank you very much, I'll remove it.
—SA
Basically, VFTs are needed to resolve function calls at runtime. Therefore, every time a class defines at least one method as virtual, or inherits from a base class with virtual methods that are overriden anywhere, that class will probably need a VFT.

Understand however, that it is the class that needs the VFT, not each instance of the class! The instance will then only contain one additional pointer that points to the correct VFT for that class. So if you have three instances Circle circle1, circle2, circle3;, each of them will have one pointer to the one and only VFT of the Circle class. If you then define another derived class Square, instances of that class will contain VFT pointers to the Square VFT. Then you can store Circles and Squares in a collection as Shape pointers, and call virtual functions on all. Doing so will reference the stored VFT pointer to obtain the correct function pointer for each instance.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900