Is it possible to access private members of a class?

前端 未结 4 1271
既然无缘
既然无缘 2020-12-06 21:14

Is it possible to access private members of a class in c++.

provided you don\'t have a friend function and You don\'t have access to the class def

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 22:00

    Well I might be talking rubish, but I think you could try to define a "twin" class with same members as the class you want to modify but different public/private modifiers and then use reintepret_cast to cast the original class to yours in which you can access the private members.

    Its a bit hacky ;-)

    A bit of code to explain the idea:

    class ClassWithNoAccess 
    {
    public:
      someMethod();
    
    private:
      int someVar;
    };
    
    class ClassTwin 
    {
    public:
      someMethod();
    
    public:
      int someVar;
    }
    

    and somewhere in the code:

    ClassWithNoAccess* noAccess = new ClassWithNoAccess();
    ClassTwin* twin = reinterpret_cast(noAccess);
    twin->someVar = 1;
    

    edit: so like someone already wrote before, this might work but the standard does not guarantee the order of the variables with public and private modifier will be the same

提交回复
热议问题