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

C++
class abc
{

public: int a;
       virtual void fun1();
};

class b: public abc
{
  public: int b;
          virtual void fun2();
};

int main()
{
   abc obj1,obj2,obj3;
   return 0;
}

here i created 3 objects for class abc, so here how many vptrs will be created?
Posted
Updated 21-Feb-15 7:31am
v2

My bet is none - why would the compiler generate any code when there's no observable output of the program?
 
Share this answer
 
Id depends how you count them. If you mean pointers to the virtual function table, it's important to understand: you need one pointer per class (without multiple inheritance I'll mention below), but you have to have a copy of such pointer everywhere the instance has to use the virtual table, which is needed to call virtual functions, to dispatch the call to right implementation, using the late binding mechanism.

But the number of unique pointer values is no more than the number of classes. Remember also that you can have many classes not having vtable at all.

From the other hand, this is true unless you don't use multiple inheritance (not your case though).

One thing (poorly understood by many) is that when you type cast some runtime type of some class instance to some different compile-time type, the pointer is shifted, in general case, in presence of multiple inheritance. This happens because, in C++, the fragments of vtables combine as the result of inheritance. For single inheritance, new methods are just appended to the table, but with multiple inheritance, you have to put together vtables from unrelated sources. This is just a hint to understanding it.

—SA
 
Share this answer
 
v3
Comments
CPallini 21-Feb-15 13:32pm    
5.
Sergey Alexandrovich Kryukov 21-Feb-15 13:37pm    
Thank you, Carlo.
—SA

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