How does the vptr work and can point to vtables of 2 classes?

15 hours ago 3
ARTICLE AD BOX

I want to make something like a virtual table and virtual pointer, but manually, to get a better understanding of virtual pointers and tables.

But, I encountered a problem with making the virtual pointer.

The class A has vtableA, and class B has vtableB. The __vptr in class B is inherited from class A, and the constructor tries to redirect it to vtableB, so with this pointer it will be possible to call B's method implementation, not A's, even though the pointer to the object of class B is of A data type.

However, I am getting an error:

a value of type "void (B::**)()" cannot be assigned to an entity of type "void (A::**)()"

class A { public: // Imagine that this is a hidden virtual table of A void(A::* vtableA[1])() = {&A::sound}; // this is a hidden pointer to virtual table of A void(A::**__vptr)() = vtableA; A() { __vptr = vtableA; } /*virtual*/ void sound() { cout << "Method A: ???" << endl; } }; class B : public A { public: // and this is a hidden virtual table of B void (B::* vtableB[1])() = {&B::sound}; B() { __vptr = vtableB; // error } void sound() // override { cout << "Method B: Meow" << endl; } };

If it is impossible to redirect __vptr to point at the virtual table of a derived class because the types do not match, how then is the virtual pointer implemented internally?

Does it have a special data type? Is it not a regular pointer-to-function, but something else?

I think if only __vptr would not depend on the data type to whom the pointer to a method belongs, that may work as I think.

Read Entire Article