More on chapter 10
Construction
- The base class constructor is called first, unless you call it with the ctor-initializer
- other members are constructed.
- The constructor is executed.
Destruction is performed in the opposite order.
- We will discover later that destructors should be marked as virtual.
Marking an item as virtual
- This tells the compiler that you plan to override this function in a future class.
- And makes things work differently.
- Without
virtual
in a previous class, a function definition is name hiding.
- With
virtual
the run time system will use dynamic binding
- Associated with each instance of the class is a table (vtable).
- This points to the proper function to call.
- When a reference or pointer to an instance of a class is passed, the runtime system consults the vtable to find what function to call.
- Without the vtable, the bindings are done at compile time.
- Passing as a value will not consult the vtable.
- Vtables add to the cost of the class
- They take up more space.
- They take more time to call.
- In java everything is virtual
- In c++ only mark things as virtual if needed (or you don't mind the hit)
We will build arrays of pointers to objects in hierarchies.
- So we want to make sure we call the proper destructor.
- Therefore the destructor should ALWAYS be declared as virtual.
- In every class that might be derived.