Skip to content

Instantly share code, notes, and snippets.

@baiyanhuang
Created July 16, 2012 02:22
Show Gist options
  • Save baiyanhuang/3120006 to your computer and use it in GitHub Desktop.
Save baiyanhuang/3120006 to your computer and use it in GitHub Desktop.
Test the vptr position in object model
sizeof(Base)=16
sizeof(Derived)=16
0x7fffd1303400
0x7fffd1303408
vptr is at the beginning? true
sizeof(Base)=16
sizeof(Derived)=16
0x7fffd1303400
0x7fffd1303408
vptr is at the beginning? true
sizeof(Base)=8
sizeof(Derived)=8
0013FF70
0013FF74
vptr is at the beginning? true
#include <iostream>
#include <cstdio>
#include <cassert>
using namespace std;
void printP( const void* p)
{
printf("%p\n", p);
}
class Base
{
public:
virtual ~Base(){}
int a;
};
class Derived: public Base
{
public:
virtual ~Derived() {}
};
int main()
{
cout << "sizeof(Base)=" << sizeof(Base) << endl;
cout << "sizeof(Derived)=" << sizeof(Derived) << endl;
Base b;
const char* str = (reinterpret_cast<int*>(&b) == &b.a) ? "false" : "true";
printP( reinterpret_cast<void*>(&b));
printP(reinterpret_cast<void*>(&b.a));
cout << "vptr is at the beginning? " << str << endl;
}
@baiyanhuang
Copy link
Author

  • Even both base and derived class have virtual functions, in derived class there is only 1 copy of vptr (in this case the base classes doesn't hold one)
  • seems, g++ and vc++ implementation put the vptr at the begining, not the end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment