More on Inheritance
Objectives
We would like to :
Notes
A new access specifier
protected
is somewhere between private and public.
It is used exclusively for inheritance.
A class instance has access to everything
A derived class has :
Full access to anything declared public
Full access to anything declared protected
No access to anything declared private
A non-related class has access to public and nothing else.
Protected is intended for
Utility members that derived members can use.
But since anyone can derive a class from your class (unless you use final), protected members are essentially public members.
And protected tends to break encapsulation, but that is big time OO theory.
The literature is mixed about protected
It is there so use it
It is bad, don't use it.
I tend to believe the later.
final
Along with
protected
comes
final
this is a specifier.
It follows the class name
class FighterT final : public PlayerT {
More on Virtual
As we said before, virtual marks a function as one that can be replaced in derived classes.
If virtual is not provided in a parent class, the function is not replaced, but hidden.
Look at PlayerT
Class() is declared in both the parent and derived class
But it is not marked virtual
So the derived class' Class() function
hides
the base class' Class() function.
And the derived class is
NOT
allowed to mark this as
override
Virtual functions are intended to enforce an interface.
Ie derived classes can replace this, but all derived classes have one of these.
virtual only needs to be marked once
But it can be marked multiple times, ie in derived classes.
You only mark virtual in the .h file or .cpp file
I prefer the .h file.
Sometimes you don't know how to deal with a function in a base class.
So you mark declare it an mark it as virtual to force it's creation in derived classes.
In addition you set it equal to 0
virtual void LevelUp() = 0;
This creates a
pure virtual function
Classes with pure virtual functions can not be instantiated.
Derived classes MUST implement these functions.
We will discuss virtual classes and pure virtual functions more later.
Take a look at PlayerT.h, PlayerT.cpp and playerTest.cpp