virtual function table in c++

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;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值