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.
Is it possible to access private members outside a class without friend?
Yes, it is possible using pointers. See the following program as an example.
x = 3 y = 9
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. 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.
x = 5 y = 4 z = 3
/*This code is contributed by Shubham Sharma.*/
Note that 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.
This article is contributed by Ashish Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- C++ Program to swap two members using Friend Function
- How to access private/protected method outside a class in C++
- Can C++ reference member be declared without being initialized with declaration?
- Friend class and function in C++
- Initialization of data members
- Static data members in C++
- Memory Allocation in Static Data Members in C++
- Structure Member Alignment, Padding and Data Packing
- C++ | friend keyword | Question 1
- C++ | friend keyword | Question 2
- Count the number of objects using Static member function
- Publicly inherit a base class but making some of public method as private
- Can virtual functions be private in C++?
- Can a constructor be private in C++ ?
- Are array members deeply copied?
- Flexible Array Members in a structure in C
- Different ways to Initialize all members of an array to the same value in C
- Some interesting facts about static member functions in C++
- Const member functions in C++
- Is sizeof for a struct equal to the sum of sizeof of each member?
Improved By : auspicious_boy