[ Team LiB ] |
![]() ![]() |
Gotcha #4: Failure to Distinguish Overloading from Default InitializationFunction overloading has little to do with default argument initialization. However, these two distinct language features are sometimes confused, because they can be used to produce interfaces whose syntax of use is similar. Nevertheless, the meanings of the interfaces are quite different:
class C1 { public: void f1( int arg = 0 ); // . . . };
// . . . C1 a; a.f1(0); a.f1(); The designer of class C1 has decided to employ a default argument initializer in the declaration of the operation f1. Therefore the user of C1 has the option of invoking the member function f1 with an explicit single argument or with an implicit single argument of 0. In the two calls to C1::f1 above, the calling sequences produced are identical.
class C2 { public: void f2(); void f2( int ); // . . . };
// . . . C2 a; a.f2(0); a.f2(); The implementation of C2 is quite different. The user has the choice of invoking two entirely different functions named f2, depending on the number of arguments passed. In our earlier example, the meanings of the two calls were identical. Here they're completely different, because they invoke different functions. An even greater difference between the two interfaces is evident if we try to take the address of the class members C1::f1 and C2::f2:
void (C1::*pmf)() = &C1::f1; //error!
void (C2::*pmf)() = &C2::f2;
With our implementation of class C2, the pointer to member pmf will refer to the f2 that takes no argument. The variable pmf is a pointer to member function that takes no argument, so the compiler will correctly choose the first member f2 as the initializer. With class C1, we'll get a compile-time error, because only one member function is named f1, and that function takes an integer argument. Overloading is generally used to indicate that a set of functions has common abstract meaning but different implementations. Default initialization is generally used for convenience, to provide a simplified interface to a function. Overloading and default argument initializers are distinct language features with different intended purposes and behavior. Distinguish them carefully. (See also Gotchas #73 and #74.) |
[ Team LiB ] |
![]() ![]() |