Lecture Notes for Introduction to Computer Science II
7 June 2001 - Function Overloading
- parts of the function - the signature
- function name
- number, order, and types of the function arguments
- not the return type, not the argument names
- two signatures are the same if they agree in every aspect - otherwise,
they're different
- two functions are the same only if they have the same signatures
- two different signatures mean two different functions
- overloaded functions agree in name but have different signatures
-
bool find(int i)
and bool find(string s)
- used sparingly overloading functions is a useful technique
- try to vary the signatures by type, not by number or order
- for example
find(int)
, find(string)
, find(char *)
- there's (almost) nothing to remember - easy to use
- varying by order can get confusing, particularly with more than two
arguments
- varying by number can also be confusing
- watch out for bad interactions with other c++ features, particularly
with type conversions
- constructor overloading
- constructors are functions, so they can take arguments
- the arguments can be used to help determine how class members are
initialized
- being functions, constructors may be overloaded
- the calling syntax puts the parameter list on the variables
- for example
-
class gear { gear(int cogs) { . . . } . . .};
-
gear g(3);
- several different constructors may be called using the function
overloading rules
- for example
-
class gear { gear() { . . . } gear(int cogs) { . . . } . . .};
-
gear g, g2(3);
- be careful - it is an extremely annoying error to use
gear g();
when you meant gear g;
This page last modified on 6 June 2001.