← Writing

February 6, 2016

How To Access private member variables of a class without using its public member functions? Answered Using C++

How To Access private member variables of a class without using its public member functions? Answered Using C++

Today I am going to show you how to access private member variables of a class without using its public functions.

Method 1: Using friend function

#include<iostream>
using namespace std;
class A
{
int a;
friend void seta(A &ob,int x);
friend int geta(A &ob);
};
void seta(A &ob,int x)
{
ob.a=x;
}
int geta(A &ob)
{
return ob.a;
}
int main()
{
int x=10;
A obj;
seta(obj,x);
cout<<geta(obj); // 10
return 0;
}
OUTPUT:
10

Method 2: Using inheritance

#include<iostream>
using namespace std;
class A
{
int a;
protected:
void seta(int x)
{
a=x;
}
int geta()
{
return a;
}
};
class derive:private A
{
public:
void dseta(int x)
{
seta(x);
}
int dgeta()
{
geta();
}
};
int main()
{
int x=10;
derive obj;
obj.dseta(x);
cout<<obj.dgeta(); //10
}

Here the private variable a is a private member of class A. As a condition, class A has no public method to access it. A derive class inherits A privately, then exposes public functions that call A’s protected functions — giving access without violating encapsulation rules.

OUTPUT:
10

Method 3: Direct access using pointer type conversion

#include<iostream>
using namespace std;
class A
{
int a;
public:
int geta()
{
return a;
}
};
int main()
{
A obj;
int* p = (int*)&obj;
*p = 10;
cout<<obj.geta()<<endl; //10
cout<<*p; //10
}

This works only on the first member variable, and only when the pointer type matches the variable’s type.

OUTPUT:
10
10
  • access private member variable
  • c++
  • friend function
  • inheritence
  • oop