Skip to main content
Engineering LibreTexts

1.9: Accessing Data Members

  • Page ID
    34641
  • \( \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}}\)

    The public data members are also accessed in the same way given however the private data members are not allowed to be accessed directly by the object. Accessing a data member depends solely on the access control of that data member.
    This access control is given by Access modifiers in C++. There are three access modifiers : public, private and protected.

    // C++ program to demonstrate  
    // accessing of data members  
    #include <bits/stdc++.h> 
    using namespace std; 
    class Geeks {     
    
       // Access specifier     
       public:        
          // Data Members        
          string geekname;        
    
          // Member Functions()        
          void printname()        
          {           
             cout << "Geekname is: " << geekname;
          }
    }; 
    
     
    int main()
    {
         // Declare an object of class geeks
         Geeks obj1;
         // accessing data member
         obj1.geekname = "Steve Jobs";
         // accessing member function
         obj1.printname();
    
         return 0; 
    } 

    Output:

    Geekname is: Abhi

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


    1.9: Accessing Data Members is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?