[   ^ to index...   |   <-- previous   |   next -->   ]

Overloading and overload resolution

We frequently want one symbol to stand for different things; we call this "polymorphism" (from the Greek poly + morph, "many-shapes"). Overriding member functions is one mechanism for polymorphism (the same method name can invoke different code depending on the type of the object on which it is invoked).

Overloading is another example of polymorphism, with very different uses.

Both member functions and functions may be overloaded. C++ only permits overloading on the number and types of arguments:

int foo() // 1. int foo(int a) // 2. OK: different profile void foo() // 3. Illegal: ambiguous with int foo() int foo(double a) // 4. OK: different profile int foo(int a, int b) // 5. OK: different profile int Bar::foo() // 6. OK: member, not global function void Bar::foo() // 7. Illegal: ambiguous with int Bar::foo() int Bar::foo(int i) // 8. OK: different profile int Bar::foo(char c) // 9. OK: different profile

At any given call site, C++ must be able to resolve unambiguously, at compile time, which function or method is being called.

Overloading is a different concept from overriding; don't confuse them.

Note: the dynamic type of an argument is not taken into consideration when overload resolution is being computed---only the static type. This is a natural corollary of the fact that overload resolution occurs at compile time.

Overloading operators

I've already mentioned that C++ operators are already overloaded---that is, they have multiple meanings (compare integer and floating point division). We can overload almost any operator in C++. For example, let's say we decided using the symbol + for Vector concatenation (appending one after the other) was a good idea. We define the following method:

class Vector { // ... some stuff ... public: Vector operator+(const Vector& other) const; };

Last modified: Tue Aug 1 13:09:18 PDT 2000