Featured post

IBPS SO IT TRICKS TO GET FULL MARKS

JOIN GROUP-  https://www.facebook.com/groups/bankibpssoit/ If you wish to get full marks in IBPS SO IT . We will provide you the gui...

C++ Class access modifiers



POST:
  • public 
  • private
  • protected
The default access for members and classes is private.

A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function.
 
class Line {
   public:
      double length;
      
};
 
int main( ) {
   Line line; // OBJECT
 
   line.length = 10.0; // OK: because length is public
   cout << "Length of line : " << line.length;
   return 0;
}
A 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.
class Box {
   
   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;
  // 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();
 
   return 0;
}
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.
class Box {
   protected:
      double width;
};
 
class SmallBox:Box // SmallBox is the derived class. {
   public:
      void setSmallWidth( double wid );
      double getSmallWidth( void );
};
 
// Member functions of child class
double SmallBox::getSmallWidth(void) {
   return width ;
}
 
void SmallBox::setSmallWidth( double wid ) {
   width = wid;
}
 
// Main function for the program
int main( ) {
   SmallBox box;
 
   // set box width using member function
   box.setSmallWidth(5.0);
   cout << "Width of box : "<< box.getSmallWidth() ;
 
   return 0;
}
||

No comments:

Post a Comment

You will get Reply with in 24 hours