virtual function table in c++
阿新 • • 發佈:2018-11-12
what is vfptr?
The follow codes show u it.
#include <stdint.h>
#include <iostream>
class base {
public:
virtual void func1() {
std::cout << "base::func1" << std::endl;
}
virtual void func2() {
std::cout << "base::func2" << std::endl;
}
};
typedef void (base::*virtual_func)(void);
void test_virtual_table() {
char base_addredd[sizeof(base)] = {0};
base *b = new(base_addredd)base;
std::cout <<"The address prealloced is 0x" << std::hex << (intptr_t)base_addredd << std::endl;
std::cout <<"base's address is 0x" << std::hex << b << std::endl;
intptr_t **__vfptr = *reinterpret_cast<intptr_t***>(b);
virtual_func* pfuncs = reinterpret_cast<virtual_func*>(__vfptr);
virtual_func v_func1 = pfuncs[0];
virtual_func v_func2 = pfuncs[1];
std::cout << "function found by vftable" << std::endl;
(b->*v_func1)();
// maybe g++ implement virtual function table differently with virtual studio,this line will crash down
// the messageis: Segmentation fault (core dumped)
// (b->*v_func2)();
std::cout << "end" << std::endl;
void (*p_temp)(void) = (void (*)(void))(&base::func1);
p_temp();
}
int main() {
std::cout << "base's size is " << sizeof(base) << std::endl;
test_virtual_table();
return 0;
}