Skip to content

Instantly share code, notes, and snippets.

@caigen
Created October 20, 2013 05:11
Show Gist options
  • Select an option

  • Save caigen/7065284 to your computer and use it in GitHub Desktop.

Select an option

Save caigen/7065284 to your computer and use it in GitHub Desktop.
C语言实现C++中的虚函数机制
// use c to simulate the mechanism of virtual function in c++.
// designed by [email protected]
#include <iostream>
using std::cout;
using std::endl;
// C: function pointer
void fun1() {
cout << "C fun1" << endl;
}
int fun2(int in) {
cout << "C fun2" << endl;
return 0;
}
void (*(v_table[2]))() = {fun1, (void (*)())fun2};
struct A{
public:
void (*(*v_table))();
};
// C++: virtual function
class B{
public:
virtual void fun1() {
cout << "C++ fun1" << endl;
};
virtual int fun2(int in) {
cout << "C++ fun2" << endl;
return 0;
};
};
int main() {
A a;
a.v_table = v_table;
(*(*a.v_table))();
(*(int (*)(int))(*(a.v_table+1)))(0);
B b;
b.fun1();
b.fun2(0);
// in vs, you could break here, and watch the memory content of a and b.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment