invoking method of a base class in a derived class
Typically, if your specialized implementations in derived class need
to reuse the base class's generic implementation, you can use the scope
resolution operator ::.
e.g. Using scope resolution operator :: to invoke
base class Functions from derived class and
main(). demolist10_5
1 |
|
: line 37 demonstrates calling the base class function
Fish::Swim() using ::, on the other hand, line
49 in main invoke base class method from main().
derived class hiding base class's methods
overriding can take an extreme form where Tuna::Swim()
can potentially hide all overloaded versions of
Fish::Swim() available, even causing compilation failure
when overloaded ones are used.
e.g. Tuna::Swim() hides overloaded method
Fish::Swim() demolist10_6
1 |
|
: Line 33-35 demonstrates three ways to invoke
Fish::Swim() and Tuna::Swim() properly. In
addition, another 2 ways to invoke Fish::Swim() via an
instance of Tuna as follow:
use keyword
usingin classTunato unhideSwim()in classFish1
2
3
4
5
6
7
8
9class Tuna : public Fish
{
public:
using Fish::Swim;//unhide all Swim() methods in class Fish
void Swim()
{
cout << "swim fast" << endl;
}
}override all overloaded
Swim()in classTuna1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Tuna : public Fish
{
public:
void Swim(bool isFreshWaterFish)
{
if (isFreshWaterFish)
cout << "from lake" << endl;
else
cout << "from ocean" << endl;
}
void Swim()
{
cout << "swim fast" << endl;
}
}
order of constructor
Base class objects are instantiated before derived class. Thus, the
Fish part of Tuna is constructed first, so
that the protected and public members of Fish are ready for
consumption when Tuna is instantiated. Within the
instantiation of Fish and Tuna, the members
attributes are instantiated before the constructor
Fish::Fish() invoked, ensuring that members attributes are
ready before the constructor work with them.
order of destructor
When Tuna goes out of scope, the sequence of destruction
is the opposite to that of construction, It goes as this order that
derived classes are destructed before base class.
e.g. the order of constructor and destructor of base class, derived class and members thereof demolist10_7
1 |
|
output:
1 | FishDummyMember construtor |
: As output demonstrated, when an object of class Tuna
instantiated, instantiation actually start at the top of the hierarchy.
Therefore, the base class Fish part of class
Tuna is instantiated first, and in doing so, the member of
Fish, Fish::dummy is instantiated first before
Tuna's constructor. Notice that Fish::dummy is
an object of class FishDummyMember. After these, the
instantiation of Tuna continues first with instantiation of
member Tuna::dummy finally followed by the execution of the
constructor code in Tuna::Tuan(). On the contrast, the
sequence of destructor is exactly the opposite.