Processing math: 100%
Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

1.11: Private Access Specifier

( \newcommand{\kernel}{\mathrm{null}\,}\)

By default access to members of a C++ class is private.

The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

// C++ program to demonstrate private 
// access modifier

#include<iostream> 
using namespace std;

class Circle 
{ 
   // private data member 
   private: 
      double radius; 

   // public member function 
   public: 
      double compute_area() 
      {    // member function can access private 
           // data member radius 
          return 3.14*radius*radius; 
      } 

};

// main function 
int main() 
{ 
   // creating object of the class 
   Circle obj; 

    // trying to access private data member 
    // directly outside the class 
    obj.radius = 1.5; 

   cout << "Area is:" << obj.compute_area(); 
   return 0; 
} 

The output of above program will be a compile time error because we are not allowed to access the private data members of a class directly outside the class.
Output:

 In function 'int main()':
11:16: error: 'double Circle::radius' is private
         double radius;
                ^
31:9: error: within this context
     obj.radius = 1.5;
         ^

However, we can access the private data members of a class indirectly using the public member functions of the class. Below program explains how to do this:

// C++ program to demonstrate private 
// access modifier     

#include<iostream> 
using namespace std; 

class Circle 
{ 
     // private data member 
     private: 
         double radius; 

     // public member function 
     public: 
         void compute_area(double r) 
         {      // member function can access private 
                // data member radius 
                radius = r; 
                double area = 3.14*radius*radius; 

             cout << "Radius is: " << radius << endl; 
             cout << "Area is: " << area; 
         } 

}; 

// main function 
int main() 
{ 
     // creating object of the class 
     Circle obj; 

     // trying to access private data member 
     // directly outside the class

     obj.compute_area(1.5); 
     return 0; 
}

Output:

Radius is: 1.5
Area is: 7.065

Adapted from:
"C++ Classes and Objects" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY 4.0


This page titled 1.11: Private Access Specifier is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

Support Center

How can we help?