Hello again! In this video, we are going to look at overriding member functions. So we all know what
overloading a function means. We just define another function which has the same name but a different
signature. Perhaps different numbers or types of arguments. And we can do this with inherited member
functions.
So, for example, we have our Vehicle class, which has an accelerate() member function, which takes
no arguments.
And then in the Aeroplane class, the acceleration might depend on the height of the aeroplane.
So we write another function, which takes the height as an argument.
And you can do that.
So we create an aeroplane object and call this function, and it all works.
But there is one drawback, though, because of the way that C++ was designed many, many years ago.
This parent class function, which takes no arguments, is inherited by the Aeroplane class.
But you cannot actually call it from outside the class.
So if we have our aeroplane objects, we can call the member function, which takes an argument, but
we cannot call the version with no arguments. Even though the class has supposedly inherited it.
And there we are. "Function does not to take zero arguments". (Double negatives are not unavoidable!)
But anyway, this does not work.
So if we overload an inherited function in the child class, then all the other inherited member functions
are "hidden".
They cannot be called from outside the class.
And this is a big problem.
It is not very consistent with object-oriented design principles.
The idea is that the base class should be the interface to that hierarchy, to the rest of the code,
and child classes should extend the interface.
They should not remove things or hide things.
So, what can we do?
Well, one approach is to just go into the child class and define all these functions by hand. So we
can go into Aeroplane, write an accelerate() member function, which takes no arguments and just calls the
parent's function.
And this will work.
So there is our redefinition, in the child class.
And then that compiles and runs correctly. But in a big hierarchy, that is going to be a lot of work.
And if the base class keeps changing, it is going to be a bit of a nightmare keeping this up-to-date.
So in C++11, we can actually get the compiler to generate all these definitions for us.
And we do that by putting a "using" definition.
So, "using Vehicle::accelerate()". This
will cause the compiler to generate definitions for all the inherited member functions, apart from the overloaded
one.
So this means we can call them through the class again.
So here we are, we have our "using" declaration in the Aeroplane class, and now that works as well.
But that is going to be a lot easier to work with.
OK, so that is it for this video.
I will see you next time.
Until then, keep coding!