Overloading
Objectives
We would like to :
- Discuss function and operator overloading.
- Implement an overloaded constructor.
Notes
- Reference: Page 38 of your book.
- C++ allows us to have functions and operators with the same name.
- This can lead to complexities but it is a powerful thing.
- We will begin to explore this for convenience right now.
- We will be back to look it other things later.
- In c++ two functions can have the same name as long as the function signature is different
- A function signature is
- The function name
- Parameters, including type, variability and constantness.
- The number of parameters.
- The signature does not include
- The return type
- some modifiers
- Look at the Hello functions in hello.cpp.
- The compiler needs is able to deduce the function to call from the parameter list.
- But when types are coercable to multiple parameters, there is ambiguity.
- Look at the Bad functions in hello.cpp
- In this case, the compiler can't decide which function to cast the double to.
- We can also overload operators.
-
type operator symbol(parameters);
- For example:
string operator +(string a, int b);
- Defines + for a string and an int.
- Returns a string
- Computes a+b where
- a is a string
- b is an integer.
- We can overload most c++ operators.
- We will explore this in more detail later.