c++

Discussion in 'C++' started by gurpreet guppi, Jan 8, 2012.

  1. gurpreet guppi

    gurpreet guppi New Member

    Joined:
    Oct 19, 2011
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    what do you mean by public and private in c++?
     
  2. M.Hanif

    M.Hanif New Member

    Joined:
    Oct 20, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Solapur
    I think Public means any body of function can access member function and data member
    private means only class body can access member function and data memb
     
  3. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    I'd add that you can use private members to "hide" data types from multiple folks working on a project. Perhaps group A devises the class while group B is only given the function members.

    Code:
    class foo {
    
       public : foo(const int &init_value = 0) { 
                     // constructor
                     private_data.int_val = init_value; 
                  }
    
                  void setInt(const int &new_value) { 
                     // accessor member function
                     private_data.int_val = new_value; 
                  }
    
                  int some_value; // directly accessible to each object of foo
    
       private : typedef struct {
                       int int_val;
                   } pd;
     
                   pd private_data; // only accessible by accessor member 
                                    // functions
    };
    
    int main() {
    
       foo test; // instantiate an object
       test.setInt(50); // use accessor function to modify
                        // private data
    
       test.some_value = 10;  // ok; data member is public
    
       return 0;
    }
    If group B were only given the member functions, they'd never know that setInt was actually modifying a structure.

    HTH
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice