Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling private method in C++

Tags:

This is purely a theoretical question, I know that if someone declares a method private, you probably shouldn't call it. I managed to call private virtual methods and change private members for instances, but I can't figure out how to call a private non-virtual method (without using __asm). Is there a way to get the pointer to the method? Are there any other ways to do it?

EDIT: I don't want to change the class definition! I just want a hack/workaround. :)

like image 253
Luchian Grigore Avatar asked Jul 29 '11 12:07

Luchian Grigore


People also ask

Who can call a private function?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

Can private methods be called in main?

Yes, we can declare the main method as private in Java. It compiles successfully without any errors but at the runtime, it says that the main method is not public.

How do I call a private method in C#?

Private Methods can only be used inside the class. To set private methods, use the private access specifier. Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.


1 Answers

See my blog post. I'm reposting the code here

template<typename Tag> struct result {   /* export it ... */   typedef typename Tag::type type;   static type ptr; };  template<typename Tag> typename result<Tag>::type result<Tag>::ptr;  template<typename Tag, typename Tag::type p> struct rob : result<Tag> {   /* fill it ... */   struct filler {     filler() { result<Tag>::ptr = p; }   };   static filler filler_obj; };  template<typename Tag, typename Tag::type p> typename rob<Tag, p>::filler rob<Tag, p>::filler_obj; 

Some class with private members

struct A { private:   void f() {     std::cout << "proof!" << std::endl;   } }; 

And how to access them

struct Af { typedef void(A::*type)(); }; template class rob<Af, &A::f>;  int main() {   A a;   (a.*result<Af>::ptr)(); } 
like image 132
Johannes Schaub - litb Avatar answered Oct 30 '22 02:10

Johannes Schaub - litb