Skip to content

A Small Runtime Rule Interface

The Course
•
35 min study

The engine enforces fixed checks itself: valid IDs, quantities in 0..1000, unique items. On top of those, a deployment may want policies: a warehouse total limit, a per-item cap, a rule that forbids renames. Which policies apply is decided when the program starts, not when it is compiled, and the engine's batch loop should not change each time someone writes a new one. That calls for runtime polymorphism: one interface the loop calls, many concrete types behind it, chosen at run time.

In C++ the interface is a base class with virtual member functions. A call through a Rule& or Rule* is dispatched to the override of the object's actual, dynamic type. The engine stores std::vector<std::unique_ptr<Rule>>: owned objects of different concrete types behind one pointer type.

Predict and run

Predict before running C++
#include <iostream>
#include <memory>

class Rule {
public:
    virtual ~Rule() = default;
    virtual bool accepts(int quantity) const = 0;
};

class Limit final : public Rule {
public:
    explicit Limit(int maximum) : maximum_(maximum) {}
    bool accepts(int quantity) const override { return quantity <= maximum_; }
private:
    int maximum_;
};

int main() {
    std::unique_ptr<Rule> rule = std::make_unique<Limit>(10);
    std::cout << rule->accepts(7) << " " << rule->accepts(11) << "\n";
    return 0;
}
Check your prediction
Text
1 0

rule has static type std::unique_ptr<Rule>, but the object it owns is a Limit. The call rule->accepts(7) looks up the override for the dynamic type and runs Limit::accepts. The = 0 makes accepts pure virtual, so Rule is abstract: you cannot create a plain Rule, only a derived class that implements every pure function. final says no class may derive from Limit, which documents intent and lets the compiler skip the dynamic lookup when it knows the exact type.

override turns a silent mismatch into an error

An override must match the base function's signature exactly, including const. Without the override keyword, a near miss declares a new, unrelated function, and calls through the base never reach it. With the keyword, the compiler checks:

C++
class Limit final : public Rule {
public:
    bool accepts(int quantity) override { return quantity <= 10; } // const is missing
};
Shell
error: non-virtual member function marked 'override' hides virtual member function
warning: abstract class is marked 'final' [-Wabstract-final-class]

The first message, an error, is the one to read: the function does not override anything, and the build stops there. The second is a warning that follows from it, since Limit still has an unimplemented pure function. Write override on every override. It costs nothing and catches signature drift when the base interface changes later.

The destructor must be virtual

std::unique_ptr<Rule> destroys its object with delete on a Rule*. If Rule's destructor is not virtual, that deletes a Limit through a pointer to its base, which is undefined behavior: typically only the Rule part is destroyed, so the derived members, such as a std::string name, are never released. Clang catches the common case. Remove virtual from ~Rule() in the example above and run it:

Shell
warning: delete called on 'Rule' that is abstract but has non-virtual destructor [-Wdelete-abstract-non-virtual-dtor]

It is a warning, on by default in Clang: the browser editor prints it above the output and then runs the program anyway, with the undefined behavior. A build with -Werror, such as the course's checker or the strict local build on Day 7, turns it into an error and refuses to build. Don't let "it still ran" persuade you: read every warning. The rule is simple: a class meant to be deleted through a base pointer gets virtual ~Base() = default;.

Slicing: polymorphism needs a pointer or reference

Dispatch works through references and pointers. Copying a derived object into a base-class value keeps only the base part and loses the override. That is called slicing:

A copy loses the derived behavior C++
#include <iostream>

class Policy {
public:
    virtual ~Policy() = default;
    virtual const char* name() const { return "default"; }
};

class Strict : public Policy {
public:
    const char* name() const override { return "strict"; }
};

void by_value(Policy policy) { std::cout << "by value: " << policy.name() << "\n"; }
void by_reference(const Policy& policy) { std::cout << "by reference: " << policy.name() << "\n"; }

int main() {
    Strict strict;
    by_value(strict);
    by_reference(strict);
    return 0;
}
Text
by value: default
by reference: strict

by_value received a new Policy built from the Policy part of strict, so its own name ran. Making the base abstract, as Rule is, turns this mistake into a compile error, because an abstract class cannot be passed by value. That is another reason to keep interfaces pure.

Keep the interface narrow and pure

The engine's real interface is virtual bool accepts(const Inventory& proposed, const Event& event) const = 0;. Each part of that line is a decision:

  • It returns a decision and nothing else, so a rule cannot partially apply anything.
  • It is const, so a rule cannot change its own configuration between calls.
  • It borrows the proposed inventory and the event for the duration of the call. A rule must not keep a pointer to either, because the proposed inventory is a staged copy that is about to be discarded or swapped away.
  • It must not print, write files or call the network. The engine can roll back its own inventory, but not effects outside it.

The compiler enforces the first two. The last two are semantic obligations: documented in the header and checked by tests, because no type can express them.

Runtime polymorphism costs an indirect call and usually a heap allocation per object. That is a fair price for configuration chosen at startup. For a callable known at compile time, such as a report predicate, Day 3 uses templates instead.

Practice

Exercise

Your turn

Give Rule two pure functions: bool accepts(int quantity) const and std::string name() const. Implement AtLeast, AtMost and MultipleOf, each configured with one number. Store AtLeast(0), AtMost(1000) and MultipleOf(5) in a std::vector<std::unique_ptr<Rule>> in that order. Write std::string verdict(const std::vector<std::unique_ptr<Rule>>& rules, int quantity) that names the first rejecting rule. Check 10, 12, -5 and 1005:

Shell
10: accepted
12: rejected by multiple of 5
-5: rejected by at least 0
1005: rejected by at most 1000
Your workspace C++
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Rule {
public:
    virtual ~Rule() = default;
    virtual bool accepts(int quantity) const = 0;
    virtual std::string name() const = 0;
};

int main() {
    // Implement three rules, store them, and print a verdict for each quantity.
    return 0;
}
Hint 1: the idea

The loop over rules only knows Rule. Each concrete class stores its own number and decides for itself.

Hint 2: a first step

Write one rule, AtLeast, with a constructor that stores its number, and store only AtLeast(0) in the vector. Make verdict loop over the rules and return the first rejecting rule's name(). With one rule, -5 should already print rejected by at least 0 and the other three accepted. Each further rule is a new class with the same shape; only its test and its name change.

Show one solution
Run the solution C++
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Rule {
public:
    virtual ~Rule() = default;
    virtual bool accepts(int quantity) const = 0;
    virtual std::string name() const = 0;
};

class AtLeast final : public Rule {
public:
    explicit AtLeast(int limit) : limit_(limit) {}
    bool accepts(int quantity) const override { return quantity >= limit_; }
    std::string name() const override { return "at least " + std::to_string(limit_); }
private:
    int limit_;
};

class AtMost final : public Rule {
public:
    explicit AtMost(int limit) : limit_(limit) {}
    bool accepts(int quantity) const override { return quantity <= limit_; }
    std::string name() const override { return "at most " + std::to_string(limit_); }
private:
    int limit_;
};

class MultipleOf final : public Rule {
public:
    explicit MultipleOf(int step) : step_(step) {} // Require step > 0.
    bool accepts(int quantity) const override { return quantity % step_ == 0; }
    std::string name() const override { return "multiple of " + std::to_string(step_); }
private:
    int step_;
};

std::string verdict(const std::vector<std::unique_ptr<Rule>>& rules, int quantity) {
    for (const auto& rule : rules) {
        if (!rule->accepts(quantity)) { return "rejected by " + rule->name(); }
    }
    return "accepted";
}

int main() {
    std::vector<std::unique_ptr<Rule>> rules;
    rules.push_back(std::make_unique<AtLeast>(0));
    rules.push_back(std::make_unique<AtMost>(1000));
    rules.push_back(std::make_unique<MultipleOf>(5));
    for (int quantity : {10, 12, -5, 1005}) {
        std::cout << quantity << ": " << verdict(rules, quantity) << "\n";
    }
    return 0;
}
Text
10: accepted
12: rejected by multiple of 5
-5: rejected by at least 0
1005: rejected by at most 1000

verdict borrows the vector by const&, so it can call every rule without taking ownership, and it stops at the first rejection, which is why -5 names at least 0 rather than also failing the multiple check. MultipleOf documents a precondition: a step of zero would divide by zero, which is undefined behavior, so a real configuration loader must reject it before constructing the rule. The checkpoint next proves, with a counter, that owned rules are destroyed exactly once.

Was this article helpful?

Your response is saved on this device.