This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
2. Introduction
• One of the more powerful features for code readability
and usability is that of overloading.
• Like most things, it can be used for both good and evil.
• In this lecture, we are going to look at one particular
flavour of overloading.
• Method overloading.
• In the next lecture we will look at a particulary C++
feature.
• Operator overloading.
• Here be dragons
3. Methods in C++
• A method in C++ is not uniquely identified by its name
alone.
• Each method has a method signature, consisting of two
elements.
• The name of the method
• The order and type of its parameters.
• Together, these act as the unique identifier for a C++
method.
• The following thus are two different methods:
• addTwo (int x, int y);
• addTwo (float x, float y);
4. Method Overloading
• The process of providing more than one method with the
same name is called method overloading.
• We say that these methods have been overloaded.
• Overloading makes sure that we can provide a consistent
and clear interface to our methods regardless of the
parameters type.
• We don’t need addTwoInts and addTwoFloats, for example.
5. Method Overloading
• We have already seen this a little bit in constructors.
• It is very good practise to overload constructors give all sensible
ways in which an object can be instantiated.
• It is not a feature unique to constructors.
• Any method can be overloaded.
• There are only two requirements.
• The parameter lists must be unique for each overloaded method
• This means unique as in the order and type of the parameters.
Identifiers do not count for this.
• The return type must be the same for all overloaded functions.
• These rules are just as true for Java as they are for C++.
6. Method Overloading
• The compiler works out which of the methods to call
based on the parameters it is passed.
• It will check for the method that has a matching signature.
• It will execute that method only.
• If no matching signatures are found, a compile-time error
will be displayed.
• Often with a less than transparent message!
7. Method Overloading
int add_nums (int one, int two) {
return one + two;
}
int add_nums (float one, float two) {
return (ceil (one + two));
}
int main() {
int answer_one, answer_two, answer_three;
answer_one = add_nums (1, 2); // Fine
answer_two = add_nums (1.0f, 2.0f); // Fine
answer_three = add_nums (1.0f, 2) // Error
}