Virtual Methods
- You can prevent classes from deriving from a given class by adding the keyword final
- To do true function replacement we need the keyword
virtual
- This marks a function for replacement.
- How does virtual work?
- When normal member functions are implmeneted, they are "bound" at compile time.
- This is called static binding or early binding.
- The compiler decides, based on the type at compile type what function to bind.
- With virtual functions it works differenty
- Each instance carries along a vtable or table of where to find the virtual functions.
- At run time, the run time system determines which function to call based on this table.
- This is called dynamic or late binding.
- See Figure 10-4, page 347 in the book.
- This type of function
- Takes a few instructions more to execute.
- Takes a bit more storage (probably a word per virtual function).
- So any function you wish to overload should be a virtual function.
- Destructors should be virtual
- A pointer is of type base class, but is pointing to a derived class.
- The derived class' destructor needs to be called.
- Constructors should not be virtual.
- Order of construction
- Base class is constructed
- Other members are constructed
- Constructor is called for the derived class.
- Order of destruction
- Derived class' destructor is called.
- Data members are destructed
- Base class' destructor is called.
- Once a function is declared to be virtual, it is virtual, no matter many levels of derivation are applied.
- Take a look at abstract.cpp