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.
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
- C++ Program to swap two members using Friend Function
- Friend class and function in C++
- Static data members in C++
- Initialization of data members
- Publicly inherit a base class but making some of public method as private
- Structure Member Alignment, Padding and Data Packing
- What happens when more restrictive access is given to a derived class method in C++?
- Count the number of objects using Static member function
- C++ | friend keyword | Question 1
- C++ | friend keyword | Question 2
- Different ways to Initialize all members of an array to the same value in C
- Flexible Array Members in a structure in C
- Are array members deeply copied?
- Const member functions in C++
- Can a constructor be private in C++ ?