C++ object model: calling virtual function by vptr leads to crash

Viewed 56

I've got this code snippet, it tries to call virtual function through an object's vptr (pointing to virtual function table) and uses object pointer to convert to p->vptr, like this:

#include<iostream>
using namespace std;
struct C {
    virtual int f() {
        return 7;
    }
};
typedef int (*pf)();
int main() {
    C c1;
    pf *pvtable = (pf *) &c1;
    cout << (*pvtable[0])() << endl;
    return 0;
}

I used clang++14 to compile/link. On running it, programs returns 139, and no cout line is shown, seems it has crashed.

Why it doesn't work and how to fix it?

1 Answers

Why it doesn't work

You are casting a pointer-to-C to a pointer-to-int(*)().

This cast has no meaning in the C++ language and using the resulting pointer is explicitly Undefined Behavior.

and how to fix it?

There is no reliable way.

C++ does not promise the existence of a vtable pointer in any program, and if there is one C++ does not offer any method to access it.

Related