Defining of Member Functions of Class in C++

Member functions can be defined at any one of the following two places:

  1. Outside the Class
  2. 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:

  1. 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:

    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.

    For instance, consider the member functions getdata() and putdata(). They may be coded (outside the class item) as follows:

    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)

  2. 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 the item class as follows:

    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.

You may also like...

1 Response

  1. pediatra says:

    Good write-up. I certainly love this site. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *