Created
September 23, 2019 12:19
-
-
Save g10guang/41e02b116b1abb8f6b7ea7d7a5ca4b46 to your computer and use it in GitHub Desktop.
Cpp virtual function testcase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Non-virtual function will not exist in virtual function table. Because it's decided in compile-time.
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
According to this post