$\require{cancel}$
More on Inheritance
-
virtual
is the key to everything here.
- Non virtual functions are linked at compile time.
- Ie the compiler knows the type of the class instance and calls the associated function.
- Virtual functions are not linked at compile time
- When a function is marked virtual, the compiler builds a v-table for that class.
- The vtable contains a link to the possible versions of the code to call.
- Class instances "know" what they are in the hierarchy.
- When a pointer or reference to any member of the hierarchy calls a virtual function, the actual function to call is looked up in this table.
- In this way, even a reference or pointer to a base class will call the correct function in a derived class.
- This is not the case with static members.
- If you declare a function in a derived class the same as one in the base class that is not VIRTUAL, you are just hiding the base class function.
- Look at virtual.cpp
- You only need to mark a function as virtual once, it is inherited as virtual.
- But it doesn't hurt to declare derived virtual functions as virtual.
-
override
is not strictly necessary but
- It causes a warning if you attempt to override a non-virtual function.
- It serves as notice to readers that you are overriding a virtual function.
- Virtual destructors
- You need to make destructors in a class with a virtual member virtual.
- When the class is destroyed, we need to make sure both the derived destructor and the base destructor gets called.
- This will free up resources allocated at each level.
- Marking them virtual will assure that this happens.
-
virtual ~ClassType() = default;
is fine.
- Casting up and down
- Casting from a base class to a derived class is called downcasting.
- This is bad, as the base class is missing any of the derived members.
- Casting from the derived class to the base class is called upcasting.
- This causes slicing in that the derived class' members are thrown away.
- If we avoid static members, and just use pointers and references many of these problems go away, but not all of them.
- Pure virtual functions and abstract classes.
- This is a mechanizm to require derived classes to provide an interface.
- But I have no idea how to implment that interface in the base class.
-
virtual type function(parameters) = 0;
- This is a pure virtual function.
- It makes the class an abstract class.
- you can not declare an instance of an abstract class.