VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-access-private-variable-in-cpp/

⇱ How to Access Private Variable in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Access Private Variable in C++?

Last Updated : 23 Jul, 2025

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++.

Accessing Private Variables From Class 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.

Syntax of Getter

class ClassName {
private:
type var_name;public: type get() {
return var_name;
} };

Here,

  • public is an access specifier that allows access outside the class.
  • type is a data type of the value that the function will return.
  • get is a name of the public getter function (can be any name).
  • var_name is the name of private variable.

C++ Program to Access a Private Variable

The below example demonstrates the use of getter to access a private variable in C++.


Output
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.

Comment