Search code examples
c++classprivate-members

Accessing private members in a class


I need to access an object from a DLL, do some manipulations to the object and feed the object to another function. The trouble is the fields I need to change are private.

I don't want to change the private modifier for the fields in the original class because the class was written a long time ago and is used in many places. However, the place where I am manipulating the class I need most of the fields without protection (it is a hack). What is the best way to do it?

Note: I am not allowed to change the original class


Solution

  • If you can see the original class you can make a mock class with the same bit pattern and cast the original object to the mock class object

    Example below

    Original class

    class ClassWithHiddenVariables
    {
    private:
        int a;
        double m;
    
    }; 
    

    Mock class

     class ExposeAnotherClass
        {
        public:
            int a_exposed;
            double m_exposed;
        };
    

    When you want to see members of the ClassWithHiddenVariables object, use reinterpret_cast to cast to ExposeAnotherClass

     ClassWithHiddenVariables obj;
        obj.SetVariables(10, 20.02);    
        ExposeAnotherClass *ptrExposedClass;
        ptrExposedClass = reinterpret_cast<ExposeAnotherClass*>(&obj);  
        cout<<ptrExposedClass->a_exposed<<"\n"<<ptrExposedClass->m_exposed;