Pergunta

Is it possible in C++ to have one vtable shared by multiple classes? As per my understanding if a class is having a virtual function then it will generate a vtable.So every class should have its own vtable.

Foi útil?

Solução 2

Polymorphism could be implemented several ways. And vtables could also be implemented several ways. But usually in following case

class A {
    virtual foo(){}
}

class B : public A {
    virtual foo(){}
}

class C : public B {
    void fooNonVirtual(){};
}

classes B and C should have the same vtable.

Example:

A *a = new A;
B *b = new B;
C *c = new C;
a->foo(); // A::foo is called
((A*)b)->foo(); // B::foo is called
((A*)c)->foo(); // B::foo is called

foo for a and b calls different methods because A and B has different vtables. For b and c the same method is called. So compiler could make some optimization and create only one vtable for B and C classes.

fooNonVirtual is not virtual and do not require vtables at all.

Outras dicas

Vtables are an implementation detail. C++ doesn't have vtables, it has virtual functions. Vtables just happen to be the most common (if not only) implementation, and the details differ.

What is it that you actually want to achieve?

You can do

typedef some::Class AnotherClass;

and then these classes would share.

Also, inheritance could - at least theoretically - result in the sharing of vtables.

A vtable is basically a table of virtual functions, so if the two classes have the same virtual functions, it seems pretty straightforward to share the vtable.

struct Class1
{
    virtual void func() { /* whatever */ }
};

struct Class2 // can share the vtable with Class1
{
    void nonvirtual_func() { /* whatever */ }
};

However, vtable may also contain other info (e.g. the stuff returned by typeid) - in this case, sharing the vtable is impossible. Some compilers have an option to disable RTTI and typeid - so that setting may affect the answer to the question.

It's not really clear what is being asked. A single class may have many different vtable, depending on how it is used. And the compiler will merge the vtables of several classes in a hierarchy. For example:

struct VB { virtual ~VB() = default; };
struct L : virtual VB {};
struct R : virtual VB {};
struct D : L, R {};

In this scenario, the vtable for VB will be different depending on whether you instantiate an L, and R or a D. On the other hand, in an object with the most derived type D, both D and the base class L will probably share the same vtable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top