8. Inheritance and Virtual Functions
28/02/23
Inheritance
- Models the 'is-a' relationship. The sub-class object is-a type of base class object
- Be sure that inheritance really is what you want before use it
- Define a new class in terms of a current class
- Uses the
:
notation. Equivalent of Javas extends
class MyClass : public MySuperClass
{
}
- Can have different access rights;
public
->protected
->private
Virtual Functions
Cost of flexibility
Adding a virtual function to a class may make the objects of that class bigger
Looking up which function to call at runtime is slower when functions are virtual
- Why the default is to not have virtual functions
Even if a function is virtual, you can still call the base class version from the sub-class version.
Can use the scoping operator to call global functions or access global variables
::
with nothing before itAlso used to denote a function is a class member in a definition
Left of scoping operator is
- blank - to access a global variable/function
- class name - to access member of that class
- namespace name - to use that namespace
Inheritance and constructors
- Construction occurs in the order; base class first, then derived class
- Destruction occurs in the order; derived class first, then base class
- Derived classes part of the object can always assume that base class part exists
- They will NOT exist/be initialised when the base class constructor/destructor is called
- Do not call virtual functions from the constructor or destructor
Virtual Destructors
- If destructor is NOT
virtual
then it will NOT be called if the object is destroyed through a base class pointer, reference or function - But if you make destructor
virtual
then the objects of that class will have a (hidden) vtable pointer