Defining of Member Functions of Class in C++
Member functions can be defined at any one of the following two places:
- Outside the Class
- Inside the Class
It is obvious that, irrespective of the place of definition, the function should perform the same task. Therefore, the code for the function body would be identical in both the cases. However, there is a subtle difference in the way the function header is defined. Both these approaches are discussed in detail as follows:
- Outside the Class Definition:
Member functions that are declared (with the help of prototypes) inside 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.However, an important difference between a member function and a normal function is that a member function incorporates a membership “Identity label” in the header. This labels tells the compiler which class the function belongs to. The general form of a member function definition outside the class is:return-type class-name::function-name(argument declaration) { function-body }
The membership label
class-name::
tells the compiler that the functionfunction-name
belongs to the classclass-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.For instance, consider the member functions
getdata()
andputdata()
. They may be coded (outside the class item) as follows:void item :: getdata(int a, float b) { number = a; cost = b; } void item :: putdata() { cout << "Number :" << number << endl; cout << "Cost :" << cost << endl; }
Since, these functions do not return any value, their return-type is void.
Note:
1) Several different classes can use the same function name. The membership label will resolve their scope
2) Member functions can access the private data of the class. A non-member function cannot do so. (However, an exception to this rule is a friend function discussed later)
3) A member function can call another member function directly, without using the dot operator (The use of dot operator in case of class is discussed later) - Inside the Class Definition:
Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. For example, we could define theitem
class as follows:class item { int number; float cost; public: void getdata(int a, float b) //declaration void putdata() //definition { //inline function cout << "Number :" << number << endl; cout << "Cost :" << cost << endl; }
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.
Good write-up. I certainly love this site. Thanks!