1

I have a class A having a number of Private/Public member functions/variables. I have added a new private member function to it. As part of a testing the newly added method, I need to invoke the private member function from my test class. In the case of member variables I have seen an example like below:

#include <iostream>
using namespace std;

class test
{
   private:
          int myInt;
   public:
          int getInt () {return myInt;}
};

int main ()
{
   test t;
   int* p = (int*) & t;
   *p = 20;
    cout << t.getInt ();
}
Output:20

Is there any reliable way I can access the private member function such that there is no code modification in the class A?

object
  • 796
  • 1
  • 12
  • 21
  • 2
    _" such that there is no code modification in the class A?"_ Nope! – πάντα ῥεῖ Dec 30 '14 at 12:15
  • No, either you use dirty tricks (probably U.B.) like the one you are using in the example code you provided, or you tweak the class. (BTW, I see no class A in your code.) – gd1 Dec 30 '14 at 12:19
  • As you've shown, there are ways, but you'll wind up hanging out with unseemly types, method hookers in platform-dependent shoes, and data dealers pushing used libraries. If it's for unit testing, you have more options, as rightfold points too. – dwn Dec 30 '14 at 15:12

1 Answers1

0

You can change class access modifiers with macro #define private public for testing, but it isn't good idea. I think you need to review test approach

sliser
  • 1,645
  • 11
  • 15