Overriding Member Functions


  • The derived class can have member functions, which has the same name as the member functions of the base class.
  • The following example shows the manipulation of data storage object called stack.
  • The stack is basically an array of integers.
  • The restriction here is that the data is stored and removed from the same end. Hence, the last data stored is the first to be removed. Hence, you say that it follows LIFO (Last in first out) logic.
  • You use the function push( ) for storing values into the stack and pop( ) to remove data values from the stack.
  • In the example, the base class has two functions - push( ) to store values into the stack and pop( ) to remove values from the stack. Since the stack is an array of integers, an erroneous result is obtained if you try to push values into a full stack (add values to the array after the maximum index) or pop values from an empty stack (No values have been stored in the stack). Hence top must have values in the range 0 to MAX.
  • But, you do not check the value of top in the base class. Hence, a second class stack2 is derived from the class stack. So, stack is the base class and stack2 is the derived class.
    Example
  • The derived class stack2 has the same functions as the base class.
  • When the push() function is called by an object of the derived class, the function described in the derived class is executed.
  • Hence, you say the derived class member functions override the base class member functions. The range of top is checked in the member function of the derived class and hence the correct values can be obtained.
  • If the value of top is out of range, an error message is given and the program is terminated.
  • Note that the derived class functions call the base class functions through the statements stack:: push(var) and return stack:: pop();
  • The scope resolution operator (::) is used for this purpose. Using this operator allows us to specify exactly what class the called function is a member of.


Constructors and Destructors << Previous

Next >> Containership

Our aim is to provide information to the knowledge seekers.


comments powered by Disqus


Footer1