We'll start by covering function overloading and operator overloading, two mechanisms in C++ (and many other langugages) that allow the use of single names (or operators) to correspond to potentially many different function implementations depending on the types they are used with.
Next, we'll introduce inheritance, which allows us to derive one class
from another, such that the derived class automatically "inherits" member variables and functions from its base class. This is helpful both to save us work (i.e. we avoid duplicating common implementation details by putting them in a base class) and to set up the foundation for meaningful hierarchies of ADTs (more on this in the next lecture).
1: Function Overloading
In C++, multiple functions are allowed to have the same name, even within the same scope, as long as they have different parameter types and can be distinguished by the compiler (and presumably by human programmers, too!). This is called function overloading. |
2: Operator Overloading
2.1
We can also apply the concept of overloading to operators as well. For example, the In C++, we can also define what an operator should do if used on our own custom classes. Take a look:
2.1 Exercise:
Pixel Operator Overloads
Let's upgrade
Implement each operator (as a non-member function) so that the code in main works correctly. Sample solution…
|
3: Delegating Constructors
3.1
Before moving on to inheritance, here's a quick miscellaneous topic that we didn't get to last time. Delegating constructors allow one constructor to call another to promote code reuse and overall elegant design.
3.1 Exercise:
Rectangle Constructors
Add two additional constructors to the
Sample solution…
|
4: Introduction to Inheritance
Let's start with a bit of motivation for inheritance and a brief introduction to the way it's available as a fundamental language feature in C++. To recap:
Let's return to apply inheritance to our |
5: Inheritance Details
5.1
Finally, let's investigate some "behind-the-scenes" details on how inheritance works.
5.1
Which of the following are true? |