Home C C++ Java Python Perl PHP SQL JavaScript Linux Online Test

Home »  C++  » Access private members of a C++ class from outside

How to access private members of a C++ class from outside

The idea is to define private as public using macro i.e #define private public

// filename :- Hack.h

class Hack 
{ 
private:    int a; 

protected:  int b; 

public:     int c; 	

}; 
// filename :- main.cpp

#include <iostream> 

#define private public        //This is the hack to access priviate variables of any class 
#define protected public     // This is the hack to access protected variables of any class  

#include "Hack.h"            // including the header file
using namespace std;

int main(int argc, char** argv) 
{ 
Hack obj; 

obj.a= 10;  // We can successully access a which is private actully 
obj.b= 20;  // We can successfully access b which is protected actually 

obj.c = 30;  

cout<<obj.a; 
cout<<obj.b; 
cout<<obj.c; 

return 0; 
	
}