Protected access is public to derived classes and private to all other classes. Even derived
classes cannot access private data or functions in their base classes.
Constructors can be initialized before the body of the constructor. At that time, the base
constructors are invoked and parameters can be passed to the base class.
Functions in the base class can be overridden in the derived class. If the base class func-
tions are virtual, and if the object is accessed by pointer or reference, the derived class’s
functions will be invoked, based on the runtime type of the object pointed to.
Methods in the base class can be invoked by explicitly naming the function with the pre-
fix of the base class name and two colons. For example, if Doginherits from Mammal,
Mammal’s walk()method can be called with Mammal::walk().
In classes with virtual methods, the destructor should almost always be made virtual. A
virtual destructor ensures that the derived part of the object will be freed when delete is
called on the pointer. Constructors cannot be virtual. Virtual copy constructors can be
effectively created by making a virtual member function that calls the copy constructor.
Q&A ....................................................................................................................
Q Are inherited members and functions passed along to subsequent generations?
If Dogderives from Mammal, and Mammalderives from Animal, does Doginherit
Animal’s functions and data?
A Yes. As derivation continues, derived classes inherit the sum of all the functions
and data in all their base classes, but can only access those that are public or
protected.
Q If, in the preceding example,Mammaloverrides a function in Animal, which
does Dogget, the original or the overridden function?
A If Doginherits from Mammal, it gets the overridden function.
Q Can a derived class make a public base function private?
A Yes, the derived class can override the method and make it private. It then remains
private for all subsequent derivation. However, this should be avoided when possi-
ble, because users of your class will expect it to contain the sum of the methods
provided by its ancestors.
Q Why not make all class functions virtual?
A Overhead occurs with the first virtual function in the creation of a v-table. After
that, the overhead is trivial. Many C++ programmers feel that if one function is vir-
tual, all others should be. Other programmers disagree, feeling that there should
always be a reason for what you do.
404 Day 12