Coupon Accepted Successfully!


Member Function and Non-Member Function

So far we used non-member function main() for declaring objects and calling member functions. Apart from main() function other non-member functions can also be used. The member function can also invoke a non-member function and vice versa. When a member function calls a non-member function, it is necessary to put its prototype inside the calling function or at the beginning of the program. It is a better practice to put prototype at the beginning of the program that is visual to the entire program. It is also possible to put definition of the non-member function before class declaration. This method allows member function to invoke outside non-member function without need of prototype declaration. But this approach creates problem when an outside non-member function attempts to invoke member function.

We know that member functions can be called using object of that class. If a non-member function is defined before class declaration, it is not possible to create an object in that function. Hence, the best choice is to put prototype of the non-member function at the beginning of the program that makes easy for both non-member function and member function to call each other. The following program explains practically whatever we learned about member function and non-member function in this section.

8.35 Write a program to call a member function using non-member function.


Explanation: In the above program, moon() is a non-member function and its prototype is declared at the beginning of the program. The function main() calls function moon(). In function moon(), object j of type class mem is declared and a member function earth() is invoked. Thus, non-member function calls the member function.

Test Your Skills Now!
Take a Quiz now
Reviewer Name