Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

1.10: Public Access Specifiers

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

All the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.
Example:

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

#include<iostream> 
using namespace std;

// class definition 
class Circle 
{ 
   public: 
      double radius; 

      double compute_area() 
      { 
         return 3.14*radius*radius; 
      } 

};

// main function 
int main() 
{ 
   Circle obj; 

  // accessing public datamember outside class 
  obj.radius = 5.5; 

   cout << "Radius is: " << obj.radius << "\n"; 
   cout << "Area is: " << obj.compute_area(); 
   return 0; 
} 

Output:

Radius is: 5.5
Area is: 94.985

In the above program the data member radius is public so we are allowed to access it outside the class.

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


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

Support Center

How can we help?