Defining member function

Member function can be defined in two places
(a) outside the class definition.
(b) inside the class definition.

Outside the class definition:
  • Member functions declared inside the class defined separately outside the class.
  • Member function are defined in same way as normal function except a membership identity label.
The general form of a member function definition
<return type> <class name> : : <function name>(parameters)

:: is known as scope resolution operator which tells the compiler that the scope of function is restricted to the class name.
Several different classes can use the same function name. the membership label will resolve the scope.
These member function defined outside the class still can access the private data because there scope is with in the class.

Inside the class definition:
  • When a function defined inside the class, it is treated as inline function. 
  • Normally only small functions are defined inside the class definition.

#include<iostream.h>
class item
{
         int number;
         float cost;
         public:
         void getdata(int a, float b);
         void putdata()
        {
                  cout<<"the number"<<number;
                  cout<<"the cost"<<cost<<"\n";
         }
};

void item :: getdata(int a, float b)
{
        number=a;
        cost=b;
}
void main()
{
item x1,y1;
x1.getdata(200,300.5);
x1.putdata();
y1.getdata(300,400.5);
y1.putdata();
}

Sample Output:



Consider the another example:

#include<iostream.h>
int m=10;
void main()
{
        int m=20;
       {
             int m=30;
             cout<<"inner block";
             cout<<m;
             cout<<::m<<"\n";
        }
cout<<"outer block";
cout<<m;
cout<<::m;
}

Sample Output:

Post a Comment

Previous Post Next Post