virtual and pure virtual functions

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?

What is the point of them?
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 you want dynamic binding
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <memory>

struct Animal
{ virtual void say() const {std::cout << "...\n";} };

struct Dog : Animal
{ virtual void say() const override {std::cout << "Woof\n";} };

struct Cat : Animal
{ virtual void say() const override {std::cout << "Meow\n";} };

struct Cow : Animal
{ virtual void say() const override {std::cout << "Moo\n";} };

using Animals = std::vector<std::unique_ptr<Animal>>;

Animals populate(std::istream& in)
{
    Animals result;
    std::string animal;
    while(in >> animal)
        if (animal == "cow")
            result.emplace_back(new Cow);
        else if (animal == "cat")
            result.emplace_back(new Cat);
        else if (animal == "dog")
            result.emplace_back(new Dog);
        else
            result.emplace_back(new Animal);
    return result;
}

int main()
{
    std::istringstream input("cat cat cow dog cow foo");
    std::vector<std::unique_ptr<Animal>> animals = populate(input);
    //Even though animals contains pointer to Animal, 
    //virtual functions of derived classes are called too
    for(const auto& v: animals)
        v -> say();
}
Meow
Meow
Moo
Woof
Moo
...
http://ideone.com/eUKmSl

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.
    virtual bool filter(const foo thing) = 0;
    virtual void process(foo thing) = 0;
}
Topic archived. No new replies allowed.