Skip to main content
Engineering LibreTexts

1.10: Public Access Specifiers

  • Page ID
    34642
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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.

    • Was this article helpful?