![]() |
VOOZH | about |
In C++, Private members of a class are accessible only within the class they are declared and by friend functions, they are not accessible outside the class not even by derived classes. In this article, we will learn how to access private variables in C++.
In C++, we can access through public function. These public methods provide us with controlled access to private variables. The getter function returns the value of the private variable, and the setter function sets the value of the private variable.
class ClassName {private:type var_name;public:type get() {
return var_name;
}};
Here,
The below example demonstrates the use of getter to access a private variable in C++.
Private Variable Value : 11
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: Although in C++, it is possible to access private variables with public getter and setter functions, it is important to remember that these variables are declared private for some reason. Therefore, access to private variables should be avoided outside the class.