c++ - Accessing private virtual functions within same class -
i asked, using code , writing in extractmultadd()
function, return variable.x
variable.y
variable.add()
, variable.multiply
. understand basic concept of virtual tables , when created, despite best efforts, i'm not quite sure how leverage them access private virtual functions. appreciated.
#include <cstdio> #include <iostream> class multadd { private: int x; int y; virtual int add() //virtual fuction vtable created thing class { return x+y; } virtual int multiply() { return x*y; } public: multadd(){ x = 2; y = 10; } }; int extractmultadd(void* math) { return 0; } int main() { multadd variable; printf("%d\n", extractmultadd(&variable)); return 0; }
i give 2 versions choose. not follow standard, , no means portable, both work on msvc 2013, gcc 4.9, , clang 3.5 test it. second version relatively safer , more portable first one. in fact, expect rather robust.
version 1:
#include <iostream> class multadd { private: int x; int y; virtual int add() { return x + y; } virtual int multiply() { return x * y; } public: multadd() { x = 2; y = 10; } }; struct multaddcracker: multadd { int add(); int multiply(); }; void extractmultadd(multadd& v) { char* p = (char*)&v; std::cout << *(int*)(p + sizeof(void*)) << '\n'; std::cout << *(int*)(p + sizeof(void*) + sizeof(int)) << '\n'; multaddcracker* pcracker = (multaddcracker*)&v; std::cout << pcracker->add() << '\n'; std::cout << pcracker->multiply() << '\n'; } int main() { multadd v; extractmultadd(v); }
version 2:
#include <iostream> class multadd { private: int x; int y; virtual int add() { return x + y; } virtual int multiply() { return x * y; } public: multadd() { x = 2; y = 10; } }; struct multaddcracker { int x; int y; virtual int add(); virtual int multiply(); }; void extractmultadd(multadd& v) { multaddcracker& w = (multaddcracker&)v; std::cout << w.x << '\n'; std::cout << w.y << '\n'; std::cout << w.add() << '\n'; std::cout << w.multiply() << '\n'; } int main() { multadd v; extractmultadd(v); }
Comments
Post a Comment