I am having trouble understanding the concept of virtual and pure virtual functions.
What is the point of them?
In what instances would I use a virtual or a pure virtual function over a regular function?
When would I choose a pure virtual function over just a virtual function?
Calls to the virtual function is resolved at runtime.
They allows you to call functions depending on actual type of objects, not on type of pointer or reference.
In what instances would I use a virtual or a pure virtual function over a regular function?
When would I choose a pure virtual function over just a virtual function?
When you are building Abstract Base Class and either do not want to provide implementation (e.g. when there is no sensible default behavior) or vant to make sure that derived classes will overload it.
1 2 3 4 5 6 7 8 9 10
class Worker
{
public:
//We want Worker class to be base class users will derive from,
//So we can have a vector of Worker pointers pointing to all kinds of derived classes
//As we cannot possibly know what users will do in these functions
//We declare them as pure virtual. Additionally users will have to overload them.
virtualbool filter(const foo thing) = 0;
virtualvoid process(foo thing) = 0;
}