Introduction to Inheritance
- He starts the section with a semi-example.
- I would like to make it more concrete.
- This example is good
- It shows the power of inheritance
- Code reuse
- Code Extension
- Code Replacement.
- This example is bad
- It is sort of a non-cooperating version
- So some things are not done "right"
- I have built a Container class.
- It is rather silly, it is just a wrapper for a vector of ints.
- It does have an interesting feature or two however.
- I used an initializer list.
- I also used a compiler generated default constructor. (Why?)
- I don't like the data access function, but we need to get to exceptions to do this correctly.
- I did overload the [] operator.
- There are two cases of this.
- One is used for const objects.
- The other is not.
- Notice they both return a reference.
- But one is const and the other is not.
- The const is what makes a difference in the function signature.
- We will see in the derived class the difference is important.
- By the way, the [] is discussed on page 486
- It always takes a single argument.
- It really should return a value.
- However there is a fairly standard rule that says "make things behave the same".
- And what does the [] operator do?
- Have a look at Container.h and Container.cpp
- I have created a derived class from the base class.
- Note, I do not need access to the implementation code. (I can move that to another directory if you wish.
- This class demonstrates the major abilities of inheritance.
- We employ the underlying data structure and most methods.
- We override some of the existing methods.
- We augment the class by providing new methods.
- We disable existing methods.
- The new class is an EvenContainer
- Like the base class, it holds multiple integers.
- Unlike the base class, it will only hold even integers.
- To accomplish this I needed to
- Modify the constructor.
- Modify or replace the insertion operator
- Delete the variable [] operator.
- Have a look at EvenContainer.h and EvenContainer.cpp
- Notice a cool thing in main.cpp.
- Even though PrintContainer takes a Container, it can also take an Event Container.
- It prints just fine.
- But unfortunately, it can chagne the container too.
- This is an example of slicing
- We essentually passed in the base class.
- So the modifications were removed.
- We will deal with this later.