Calling private method in C++

后端 未结 12 2211
忘了有多久
忘了有多久 2020-11-27 20:02

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 chang

12条回答
  •  佛祖请我去吃肉
    2020-11-27 20:45

    For GCC it can be done by using mangled name of a function.

    #include 
    
    class A {
    public:
        A() {
            f(); //the function should be used somewhere to force gcc to generate it
        }
    private:
        void f() { printf("\nf"); }
    };
    
    typedef void(A::*TF)();
    
    union U {
        TF f;
        size_t i;
    };
    
    int main(/*int argc, char *argv[]*/) {
        A a;
        //a.f(); //error
        U u;
        //u.f = &A::f; //error
    
        //load effective address of the function
        asm("lea %0, _ZN1A1fEv"
        : "=r" (u.i));
        (a.*u.f)();
        return 0;
    }
    

    Mangled names can be found by nm *.o files.

    Add -masm=intel compiler option

    Sources: GCC error: Cannot apply offsetof to member function MyClass::MyFunction https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html

提交回复
热议问题