Review of last lecture
- last time we talked abt polymorphism
- same func, different args
- inheritance: creating a class hierarchy
- allows “refinement”
- (polymorphism) multiple versions of one thing!
- “single collection of generic things
- but it can handle all variations
- ”operator overloading”
- We can define the
+or-operator (neat!)
- We can define the
Inheritance
A parent could be a “Notes” class and the child classes “piano” and “guitar” “refines” those child nodes.
- Each of these subclasses are related / have some common properties to the parent class.
- If you have a hierarchy like A→B→C, then B is a parent of C, but semantically A is not a parent of C (according to Paco)
- Also B would be called the “base” or “parent class”
It eliminates this issue of having code that looks like this:
double get_sound_sample(note *my_note, double time_index)
{
// Computes and returns the sound value for the specified note
// and time index.
if (note->instrument_ID==0)
{
// Do the processing required to get a sound value
// for instrument 0, using the required variables
// from the CDT
}
else if (note->instrument_ID==1)
{
// Do the processing required to get a sound value
// for instrument 1, using the required variables
// from the CDT
}
else if (note->instrument_ID==2)
{
// Do the processing required to get a sound value
// for instrument 2, using the required variables
// from the CDT
}
else if ... // for as many instruments as the synthesizer
// supports (this can be hundreds!)
}by shrinking it into this:
double get_sound_sample(note *my_note, double time_index)
{
return my_note.get_sample(time_index);
}and the individual object does all the fancy implementation things!
For instance you could have a class piano : note and implement
double piano::get_sample(double time_index)
{
// piano things
return piano_sounds;
}that’s the power of OOP.
Protected variables: code is not visible outside the class hierarchy; for children classes they can access the data like any other class.
*this*refers to the pointer of the objectthisreplaces->in that we can saythis.propertyinstead ofclass->property
virtual derived classes can override this function, but otherwise it is abstract. If a derived class derives a function that is not virtual, then we cannot “refine” it.
Overriding != Overloading
- Overriding = Obscuring a previous implementation and masking it with a new one
- Overloading = having many functions of the same name but different signature.
functions that are overridden by child classes will have that function pointer changed.
so if we have a note, and a child “piano” which changes play_note, then calling an instance of play_note on a node that is instanced via new Piano will call the function the piano made as that is what play_note is pointing to.
The destructor of the immediate class will be called first, then automatically the parent node’s destructor will also be called
Then in 6.9 we talk about copyright!