Why vptr is not static

So, even though the virtual pointer is constant across objects of class why cant it be made as static. Why each derived instance is having the pointer to vtable.

Thanks,
Sanjeev
The instance has to have a pointer to the vtable so it knows which vtable to use.

The pointer itself can't be static because the object needs to be able to poll it at runtime to determine what type of object it is. A static lookup could only resolve at compile time.

Example:

1
2
3
4
5
6
7
8
9
10
class A {...};
class B : public A {...};
// assume both classes are polymorphic

void func(A* ptr)
{
   // which vtable does 'ptr' use?
   // answer: impossible to know, because it depends on the runtime status of
   //  whatever 'ptr' points to
}
The vtable is a table of pointers to functions.

Each class needs a different vtable because the vtable will be different for each class.

Different instances of a class have the same vtable.

The vtable is used to implement the Object Oriented mechanism. The call of virtual functions and RTTI will use the vtable of the object, so it needs to be available for each object. The objects vpointer is a pointer the vtable for that class.
Try to implement it in C.

Suppose
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class base{
public:
   virtual void foo();
};

class derived_a: public base{};
class derived_b: public base{};

void polymorphism(base &obj){
   obj.foo(); //obj.vptr->foo();
}

derived_a obj;
polymorphism(obj);
when you reach the `polymorphism()' function you have a `base' object, there is no way to know that it was actually a `derived_a', ¿so how could you access a class attribute?
Thank you all for your nice explanation.
Topic archived. No new replies allowed.