OOPortal OOPortal

C++ Class Construct  «Prev  Next»
Lesson 6 Overloading member functions
Objective Overload member functions in the same class.

Overloading Member Functions in C++

Member functions within the same class can be overloaded. Remember that a function is called based on its signature, which is the list of argument types in its parameter list. Consider adding to the class ch_stack a pop operation which has an integer parameter that is the number of times the ch_stack should be popped. It could be added as the following function prototype within the class:

class ch_stack {
   char pop(int n);      //within ch_stack

char ch_stack::pop(int n)
   assert(n <= top);
   while(n-- > 1)
   return s[top--];

The definition that is invoked depends on the actual arguments to pop:
data.pop();           //invokes standard pop
data.pop(5);          //invokes iterated pop

A member function is conceptually part of the type. There is no distinct member function pop for each ch_stack object.
There is quite a bit more to overloading functions, but this requires a more in-depth look at polymorphism, which is covered in the third course in the C++ for C Programmers series, Designing Reusable Code in C++.