21.4 Function Hiding in Derived Classes

I l @ ve RuBoard

Example 21-3 defines a base class with the overloaded function do_it , which comes in both integer and floating-point versions. The program also defines a derived class that contains the single integer function do_it .

Example 21-3. doit/doit.cpp
 class simple {     public:         int do_it(int i, int j) { return (i*j); }         float do_it(float f) { return (f*2);} }; class derived: public simple {     public:         int do_it(int i, int j) { return (i+j); } }; 

Clearly, when we are using the derived class and we call the integer version of do_it , we are calling the one in the derived class. But what happens if we call the floating-point version? The derived class has no floating-point do_it . Normally, if we don't have a member function in the derived class, C++ will look to the base class.

However, since a version of do_it is defined in the derived class, C++ will look to the derived class for all flavors of do_it . In other words, if one form of do_it is defined in the derived class, that locks out all forms of the function:

 int main(  ) {     derived test;       // Define a class for our testing     int i;              // Test variable     float f;            // Test variable     i = test.do_it(1, 3);   // Legal; returns 4 (1 + 3)     f = test.do_it(4.0);    // Illegal; "do_it(float)" not defined in                              // the class "derived" 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net