29. Private Access Modifiers

By | September 23, 2021

The private Members

private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member −

class Box {
   double width;
   
   public:
      double length;
      void setWidth( double wid );
      double getWidth( void );
};

Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.

Example

#include <iostream>
 
using namespace std;
 
class Box {
   public:
      double length;
      void setWidth( double wid );
      double getWidth( void );
 
   private:
      double width;
};
 
// Member functions definitions
double Box::getWidth(void) {
   return width ;
}
 
void Box::setWidth( double wid ) {
   width = wid;
}
 
// Main function for the program
int main() {
   Box box;
 
   // set box length without member function
   box.length = 10.0; // OK: because length is public
   cout << "Length of box : " << box.length <<endl;
 
   // set box width without member function
   // box.width = 10.0; // Error: because width is private
   box.setWidth(10.0);  // Use member function to set it.
   cout << "Width of box : " << box.getWidth() <<endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following result −

Length of box : 10
Width of box : 10

Leave a Reply

Your email address will not be published. Required fields are marked *