Skip to content

Instantly share code, notes, and snippets.

@g10guang
Created September 23, 2019 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g10guang/41e02b116b1abb8f6b7ea7d7a5ca4b46 to your computer and use it in GitHub Desktop.
Save g10guang/41e02b116b1abb8f6b7ea7d7a5ca4b46 to your computer and use it in GitHub Desktop.
Cpp virtual function testcase
#include <iostream>
using namespace std;
class Base1 {
public:
virtual void f() { cout << "Base1:f" << endl;}
virtual void g() { cout << "Base1::g" << endl;}
};
class Base2 {
public:
virtual void f() { cout << "Base2:f" << endl;}
virtual void g() { cout << "Base2::g" << endl;}
};
class Base3 {
public:
virtual void f() { cout << "Base3:f" << endl;}
virtual void g() { cout << "Base3::g" << endl;}
};
class Derive : public Base1, public Base2, public Base3 {
public:
virtual void f() { cout << "Derive::f" << endl;}
virtual void g1() { cout << "Derive::g1" << endl;}
};
typedef void(*Func)(void);
int main() {
Func pFun = NULL;
Derive d;
long **pVtab = (long**)&d;
// first virtual func table
pFun = (Func)pVtab[0][0];
pFun();
pFun = (Func)pVtab[0][1];
pFun();
pFun = (Func)pVtab[0][2];
pFun();
pFun = (Func)pVtab[1][0];
pFun();
pFun = (Func)pVtab[1][1];
pFun();
pFun = (Func)pVtab[2][0];
pFun();
pFun = (Func)pVtab[2][1];
pFun();
return 0;
}
// output:
// Derive::f
// Base1::g
// Derive::g1
// Derive::f
// Base2::g
// Derive::f
// Base3::g
@g10guang
Copy link
Author

According to this post

@g10guang
Copy link
Author

Non-virtual function will not exist in virtual function table. Because it's decided in compile-time.

@g10guang
Copy link
Author

cpp is not memory-safe. Non-public function will exist in virtual function table. By offset the pointer, we can call them.

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