C++ How do i get a pointer to a class' virtual function table?

184 views Asked by At

Given:

Example.h

struct Base {
    virtual ~Def() = default;

    virtual void accept(struct DerivedVisitor* v) = 0;
};

struct Derived : Base {
    int num;
    void accept(struct DerivedVisitor* v) override;
};

struct DerivedVisitor {
    virtual void visit(Derived* d) = 0;
};

Example.cpp

#include "Example.h"

void Derived::accept(struct DerivedVisitor* v) {
    v->visit(this);
}

Say that I wanted to create an instance of Derived from "scratch". As it contains a virtual function, from Base, how would i get a hold of the address to its virtual function table so that i could do something like this:

main.cpp

#include <iostream>
#include <memory>
#include "Example.h"

struct Visitor : DerivedVisitor {
    void visit(Derived* d) override {
        std::cout << d->num << std::endl;
    }
};

int main() {
    int num = 5;
    
    // Create Derived instance from scratch
    auto der = malloc(sizeof(Derived));
    auto derBytes = static_cast<char*>(der);
    new (derBytes) void*(/*HERE I NEED POINTER TO Derived VFT*/); // <------------- How?
    new (derBytes + sizeof(Base)) int(num);

    // Just to see that it works:
    Base* base = reinterpret_cast<Derived*>(der);
    Visitor visitor{};
    base->accept(&visitor);

    free(der);
    return 0;
}

Is this compiler specific? If so, I am using MinGW if anyone is familiar with it.

1

There are 1 answers

0
eerorika On BEST ANSWER

Is this compiler specific?

Yes, this is compiler specific.

There is no such thing as a "virtual function table" in the C++ language. Such table is an implementation detail.

Given that such table doesn't exist in the language, there is also no way to get a pointer to the table in standard C++. Assuming your compiler has such thing as a virtual table (which is a reasonable assumption), then it may be possible that your compiler documents a way to access it. I doubt that however. You may have to do that in assembly language.