Tuesday, February 15, 2011

Defining a member function:


Defining a member function:
   A member function can be defined mainly in two ways: They are
i) Member function inside the class body
ii) Member function outside the class body

a) Member Function Inside the class body:
    In this case, a member function is defined at the time of its declaration. The function declaration is replaced by the function definition inside the class body. This technique is applied in the case of short functions. The function defined within a class body is treated as inline function. This is illustrated by following example.
class box
   {
   private:
       float len, br, height;
   public:
     void get_data()  //function definition
             {
               cout<<"Enter length, breadth, height"<<endl;
               cin>>len>>br>>height;
             }
      float volume()    //function definition
                {    return(len*br*height);       }
   };
void main()
   {
   box b1;
   float result;
   clrscr();
   b1.get_data();
  result=b1.volume();
  cout<<"The volume is:\t"<<result;
   }

Output:
 Enter length, breadth, height  12  3  4
The volume is:  144

In this example, the functions get_data() and volume() are defined within body of class box.

b) Member Function Outside the class body:
  In this technique, only declaration is done within class body. The member function that has been declared inside a class has to be defined separately outside the class. The syntax for defining the member function is as
   return_type  class_name :: function_name(argument_list)
         {
          //function body
        }
  Here, class_name:: is known as a membership identity label which tells the compiler which class the function belongs to (i.e. function_name belongs to class_name). The symbol :: is called scope resolution operator.

  An example:
 class box
   {
    private:
       float len, br, height;
   public:
      void get_data();
      float volume();
   };
 void box::get_data()  //function definition outside the class body
             {
               cout<<"Enter length, breadth, height"<<endl;
               cin>>len>>br>>height; }

 float box::volume()   //function definition outside the class definition
                {    return(len*br*height);       }

void main()
   {
   box b1;
   float result;
   b1.get_data();
  result=b1.volume();
  cout<<"The volume is:\t"<<result;
      }
Output:
 Enter length, breadth, height  10 2 3
The volume is:  60

In this example, get_data() and volume() functions are member functions of class box. They are declared within class body and they are defined outside the class body. While defining member functions, box:: (membership identity label) specifies that member functions belong to the class box. Other are similar to normal function definition.

No comments:

Post a Comment