Inheritance: An Is-a Relationship
A banana is a fruit, but a lunch has a banana.
The Need for Virtual Destructors
If the destructors are not not virtual, then just the destructor corresponding to the pointer type is called.
class Brass{
virtual ~Brass(){};
};
class BrassPlus :public Brass{
virtual ~BrassPlus(){};
};
So if a pointer points to a BrassPlus object, the BrassPlus desctructor is called.
And when a BrassPlus destructor finishes, it automatically calls the base-class constructor. Thus, using virtual desctructors ensures that the correct sequence of destructors is called.
BrassPlus dilly;
Brass* pb = &dilly;
Brass& rb = dilly;
It is always allowed for public inheritance without the need for an explict type cast. This rule is part of expressing the is-a relationship.
Things to know About Virtual Methods
- Constructors can’t be virtual.Creating a derived object only invokes a derived-class constructor, not a base constructor.
- Destructors should be virutal unless a class isn’t to be used a base class.
- Friends can’t be virtual functions because friends are not class members, and only members can be virtual functions.
How Virtual Functions Work
The usual way complilers handle virutal functions is to add a hidden member to each object. The hidden member holds a pointer to an array of function addresses. Such an array is usually termed a virtual function table(vtbl).
The vtbl holds the addresses of the virtual functions declared for objects of that class.
In short, using vrtual functions has the following modest costs in memory and execution speed:
- Each object has its size increased by the amount needed to hold an address.
- For each class, the compiler a table (an array) of addresses of virtual functions.
- For each function call, there’s an extra step of going to a table to look up an address.
Access Control: protected
The protected keyword is like private in that the outside world can access class members in a protected section only by using public class members. The difference between private and protected comes into play only within classes derived from the base class. Members of a derived calss can access protected members of a base class directly, but they cannot directly access private members of the base class.