adsense


Wednesday, 25 November 2015

C++ LANGUAGE PRIVATE MEMBERS

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE PRIVATE MEMBERS






 
The private Members 


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. 

By default all the members of a class would be private, for example in 
the following classwidth 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.

 
#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 


No comments: