How to Access Private Variable in C++

Anam Javed Feb 02, 2024
  1. Access Private Variable in C++
  2. Access Private Variable in C++ Using Public Member Functions
  3. Access Private Variable in C++ Using friend Functions or Classes
  4. Access Private Variable in C++ Using Pointers to Objects
  5. Conclusion
How to Access Private Variable in C++

In C++, class members are private by default, meaning they can only be accessed within the class they are declared in. However, there are several techniques to access private variables from outside the class.

In this article, we’ll explore different methods to achieve this, providing detailed examples for each.

Access Private Variable in C++

Encapsulation protects sensitive and essential data from unauthorized users. The private keyword is used to achieve this phenomenon.

Along with encapsulation, the data-hiding concept is also implemented in C++. The variable declared with the private keyword in C++ signals that it can be accessed only by the member functions of its class.

Any object or function cannot directly access it. Let’s look at the example below.

#include <iostream>
using namespace std;

class shape {
 private:
  double r;

 public:
  void area(double rr) {
    r = rr;

    double ar = 3.14 * r * r;

    cout << "Radius is: " << r << endl;
    cout << "Area is: " << ar;
  }
};

int main() {
  shape obj;
  obj.area(1.5);

  return 0;
}

Output:

Radius is: 1.5
Area is: 7.065

Besides a friend function or member function of the class, no entity can access the private data member of the class. Here, the variable r is accessed by the member function of the class area().

The area() function calculates the circle’s area by accessing the class’s private data member.

The object of the class is created in the main function of the class. Through this object, the class member function is accessed, and the area of the circle is computed.

The friend function alone is not the way to access the private data members. Besides that, private variables are also accessed outside of a class using pointers.

This method of using pointers to access private data members is a loophole in C++. Read along to learn more about it.

Access Private Variable in C++ Using Public Member Functions

A private member variable or function in C++ cannot be accessed or seen outside the class. The main concept of C++ is its unique feature of the security of data.

A private data member can only be accessed by the class in which it is created and the friend function of its class.

One of the most common and recommended ways to access private variables is through public member functions. These functions serve as interfaces to interact with the private members of a class.

The syntax for declaring a public member function in C++ is as follows:

class ClassName {
 public:
  returnType functionName(parameter1Type parameter1Name,
                          parameter2Type parameter2Name, ...) {
    // Function body
    // ...
  }
};

Here’s a breakdown of the syntax elements:

  1. public:: This keyword is an access specifier. It specifies that the members following it (in this case, the member function) will be accessible from outside the class.
  2. returnType: This is the data type that the function will return after it is called. If the function doesn’t return anything, the return type should be void.
  3. functionName: This is the name you give to the function. It should be a valid C++ identifier and follow the naming conventions.
  4. (parameter1Type parameter1Name, parameter2Type parameter2Name, ...): This is the parameter list of the function. It specifies the type and name of the input parameters that the function expects. If the function doesn’t take any parameters, you can leave this part empty or use void to indicate that it takes no arguments.
  5. {}: These curly braces enclose the body of the function. Inside the braces, you write the code that defines what the function does when it is called.

Focus on the example below to learn how public member functions of the class access the data members.

#include <iostream>
using namespace std;

class Emp {
 private:
  int sal;

 public:
  void setSal(int s) { sal = s; }

  int getSal() { return sal; }
};

int main() {
  Emp myObj;
  myObj.setSal(50000);
  cout << myObj.getSal();
  return 0;
}

Output:

50000

In the above program, the class Emp has both private and public members. sal is a private variable that two class member functions may access: setSal() and getSal().

setSal() is initializing the value of the private data member sal, and getSal() returns the value of the private data member sal. Finally, in the main method, the object of the class is created.

The object myObj accesses the member function of the class, setSal(), to pass the value to the private data member sal. At last, the class object accesses getSal() to return the sal data member.

By default, all the members of a class are private; for example, in the class shown below, w is a private member. So, it will be considered a private data member until you label a member as public or protected.

class B {
  double w;

 public:
  double len;
  void setW(double wid);
  double get(void);
};

In real-time, data is defined in the private area, and member functions in the public area to call them from outside the class, as shown in the following program.

#include <iostream>

using namespace std;

class B {
 public:
  double len;
  void setW(double wid);
  double getW(void);

 private:
  double w;
};

double B::getW(void) { return w; }

void B::setW(double wid) { w = wid; }

int main() {
  B box;

  box.len = 10.0;
  cout << "Length: " << box.len << endl;

  box.setW(10.0);
  cout << "Width: " << box.getW() << endl;

  return 0;
}

In the above program, class B has both private and public members. Here, w is a private variable that the two-class member function may access: setW() and getW().

setW() initializes the value of the private data member w, and getW() returns the value of the private data member w. The object box accesses the member function of the class.

The public variable len is accessible through the object box and is initialized with a value. setW() assigns the given value to the private data member w.

Finally, the class object box accesses getW() to return the w data member.

Output:

Length: 10
Width: 10

Access Private Variable in C++ Using friend Functions or Classes

C++ allows declaring functions or entire classes as “friends” of another class. A friend function or class has access to the private members of the class it is declared as a friend of.

A friend function is in the private or public part of the class. It can be called a normal member function without using the object.

The class object does not call it as it is not inside the scope of the class. Furthermore, it cannot directly access the class’s private and protected data members.

The friend function uses the object of the class and accesses the members using the dot operator. It can be a global function or a member of another class.

The syntax of a friend function in C++ is as follows:

class ClassName {
 private:
  // Private members

 public:
  // Public members

  friend ReturnType FriendFunctionName(ParameterType1 param1,
                                       ParameterType2 param2, ...);
};

Here’s a breakdown of the syntax elements:

  • class ClassName: This is the declaration of the class where the friend function is being declared.
  • private: This is the access specifier indicating that the members following it (in this case, private members) are only accessible within the class.
  • public: This is the access specifier indicating that the members following it (in this case, public members) are accessible outside the class.
  • friend: This keyword is used to declare that a function or an entire class is a friend of the class. It grants that function or class access to the private and protected members of the class.
  • ReturnType: This is the type that the friend function returns.
  • FriendFunctionName: This is the name of the friend function being declared.
  • ParameterType1 param1, ParameterType2 param2, ...: These are the parameters that the friend function takes. Each parameter consists of a type and a name.

Example Code (friend Function)

#include <iostream>
using namespace std;

class Dist {
 private:
  int m;

  friend int add(Dist);

 public:
  Dist() : m(0) {}
};

int add(Dist d) {
  d.m += 5;
  return d.m;
}

int main() {
  Dist D;
  cout << "Distance: " << add(D);
  return 0;
}

Output:

Distance: 5

In the above program, we can see a class Dist with private members m. We have a public constructor that is initializing the values of m.

Then, there is a friend function add(), which calculates the distance using m. The add() is a friend function that is not inside the scope of the class.

In the main method, an object of the class is created, and the add() function is passed. The add() function calculates the distance and displays the result.

friend Class in C++

A friend class is like a friend function that can be created. The friend class can access the secret and protected members of the class it is friends with.

Similar to friend functions, there is a friend class. It can access private and protected class members to which it is a friend.

Syntax:

class X {
  Data members;
  Member Functions;

  friend class Y;
};

class B {
  ……..
};

As shown in the syntax, class X is a friend of class Y. This means class Y can access the private and protected members of class X.

But this friendship is not mutual, and class X cannot access private and protected members of class Y. We must designate class X as a friend of class Y.

Also, the friendship is not inherited, so class Y will not be a friend of the child classes of class X.

Example of friend Class in C++

In this example, there are two classes. The class Ar calculates the area using the len and br variables.

This class has three private data members: arr, len, and br. The other class created is prClass, which prints the final area calculated by the member function computeArea of class Ar.

Because all the data members are private, we need to make the prClass a friend to the Ar class to print the result. The class Ar object is created inside the main function.

The area calculation is done, and the object of the Ar class is passed to the prClass function. This function is called prAr, which displays the area.

#include <iostream>
#include <string>
using namespace std;
class Ar {
  int len, br, arr;

 public:
  Ar(int l, int b) {
    len = l;
    br = b;
  };

  void computeArea() { arr = len * br; }

  friend class prClass;
};
class prClass {
 public:
  void prAr(Ar &a) { cout << "Area = " << a.arr; }
};
int main() {
  Ar a(20, 10);
  a.computeArea();
  prClass p;
  p.prAr(a);

  return 0;
}

Output:

Area = 200

Cons of Using a friend Function to Access Private Variables in C++

The most important feature of C++ is encapsulation, i.e., a grouping of data and functions. Data members and member functions work on the data together so that no outside function or class can access the data.

The encapsulation feature is compromised due to friend functions or classes being allowed to access the private members of another class. Data security comes in danger.

Access Private Variable in C++ Using Pointers to Objects

Another way to access private members is by using pointers to objects of the class. This allows direct access to private members, but it requires careful handling to ensure correctness.

Pointers access the data without a friend or class member function. Look at the example below.

#include <bits/stdc++.h>
using namespace std;

class Hello {
 private:
  int c;
  int d;
};

int main() {
  Hello a;
  int* q = (int*)&a;
  *q = 4;
  q++;
  *q = 5;
  q--;
  cout << "c = " << *q << endl;
  q++;
  cout << "d = " << *q << endl;
  return 0;
}

Output:

c = 4
d = 5

In this example, a is an object of class Hello. The class object a address is assigned to integer pointer q through typecasting.

The pointer q then points to private member c. The integer value is assigned to *q, which is c.

Then the address of the object a is increased and by accessing the memory location value 5 is assigned to d. The q-- statement sets the memory location of c.

Using the cout statement, c is displayed.

Conclusion

Accessing private variables in C++ is a fundamental concept, and it’s important to understand the different methods available. While direct access to private members can be achieved through friend functions, classes, or pointers, it’s generally recommended to use public member functions to maintain encapsulation and ensure proper data validation and error handling.

Each method has its use cases, so choose the one that best fits your specific requirements.