Tuesday, February 15, 2011

Accessing class members:


Accessing class members:
    The private data or function of a class can be accessed only through the member function of that class. The member function can access all the data and functions as usual. The public class member can be accessed from outside the class also. The public class variable and function is accessed using object name and dot operator.
Syntax for accessing public data member is
      Object_name.data_name;

Syntax for accessing public member function is
      Object_name.function_name(actual_argument_list);


An example:
 #include<iostream.h>
 #include<conio.h>
class rectangle
  {
  private:
      float len,br;
   public:
      void getdata(float l, float b) // defining member functions
            {  len=l;
                br=b;   }

      void calculate_area()
             {         cout<<"\nThe area is "<<(len*br);       }
  };

 void  main()
   {
    rectangle r1, r2;  // defining two objects
    clrscr();
    r1.getdata(10,20);  //accessing member function
    r2.getdata(15,10);
    r1.calculate_area();
    r2.calculate_area();     }

Output:
The area is 200
The area is 150

No comments:

Post a Comment