DEFINING A MEMBER FUNCTION
Member function can be defined in two places:
1. Outside the class
2. Inside the class
Outside the class
Member functions that are declared outside a class have to be defined separately outside the class. Their definitions are very much like the normal functions. They should have a function header and a function body.
An important difference between a member function and a normal function is that a member function includes a membership ‘identity label’ in the header. This label tells the compiler which class the function belongs to.
Syntax:
return-type class-name :: function-name (argument declaration)
{
Function body
}
The membership label class-name :: tells the compiler that the function “function name” belongs to the class “class-name”. That is, the scope of the function is restricted to the class-name specified in the header line. The symbol :: is called the scope resolution operator.
Example:
void item :: getdata(int a, float b)
{
number=a;
cost=b;
}
void item :: putdata()
{
cout << “number is “ << number;
cout << “cost is “ << cost;
}
Member functions have some special characteristics that are often used in the program development:
· Different classes can use the same function name.
· Member function can access the private data of the class.
· Member function can call another member function directly without (.) operator.
Inside the class
When a function is defined inside a class, it is treated as an inline function. Therefore, all the restrictions and limitations that apply to an inline function are also applicable here. Normally, small functions are defined inside the class definition.
Example :
class item
{
int number;
float cost;
public:
void getdata(int a,float b);
void putdata() // declared inside the class
{
cout << “number is “ << number;
cout << “cost is “ << cost;
}
};
PRIVATE MEMBER FUNCTION
It can only be accessed by any other member of it’s class. Even an object can’t access private function using (.) operator.
Program 6:
#include<iostream.h>
#include<conio.h>
class ABC
{
int a,b;
void put();
public:
void get();
}x;
void ABC :: get()
{
cout << "Enter a and b";
cin >> a >> b;
put();
}
void ABC :: put()
{
cout << "a = " << a << "b = " << b;
}
void main()
{
clrscr();
x.get();
getch();
}
Made By: Chaudhary Amit V.
Comments
Post a Comment