VOOZH about

URL: https://www.geeksforgeeks.org/cpp/can-we-access-private-data-members-of-a-class-without-using-a-member-or-a-friend-function-in-cpp/

⇱ Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?

Last Updated : 23 Jul, 2025

The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. 
So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Although it's a loophole in C++, yes it's possible through pointers.

Example 1:


Output
10

Example 2: 


Output
x = 3
y = 9

Explanation: In the above program, a is an object of class A. The address of the object is assigned to integer pointer p by applying typecasting. The pointer p points to private member x. The integer value is assigned to *p, that is, x. Address of object a is increased and by accessing the memory location value 9 is assigned to y. The p-- statement sets the memory location of x. Using the cout statement contains of x is displayed.
Example 3: 


Output: 
x = 5 y = 4 z = 3

 

Note: In the above way of accessing private data members is not at all a recommended way of accessing members and should never be used. Also, it doesn't mean that the encapsulation doesn't work in C++. The idea of making private members is to avoid accidental changes. The above change to data is not accidental. It's an intentionally written code to fool the compiler.

Time Complexity : O(1)

Auxiliary Space: O(1)

Comment
Article Tags: