The plug: inheritance and virtual functions#

Classes ended with one energy function, LJPotential, packaged as a class. The engine needs more than one kind: A simple molecular dynamics loop described the energy function as a plug, where the force step asks for an energy and forces, and any energy function that answers fits the same place. This chapter writes that in C++. A class Potential is the socket; LJPotential and a second energy function are two plugs; a small ForceCalculator holds any number of plugs and adds them up, without knowing which kinds it holds.

The whole program is one file, plug.cpp. The sections below show it part by part.

The socket: a class with only promises#

Listing 19 plug.cpp (the socket)#
 7// The socket: what every energy function must provide.
 8class Potential {
 9public:
10    virtual ~Potential() = default;
11    virtual double energy(double r) const = 0;
12    virtual std::string name() const = 0;
13};

Potential has no data and no formulas. It lists what every energy function must provide:

  • virtual double energy(double r) const = 0; virtual means: the version of this function that runs is chosen when the program runs, by the kind of object it is called on (the next sections show how). = 0 means Potential itself gives no version at all; every plug must supply one. A function marked = 0 is called pure virtual.

  • virtual std::string name() const = 0; the same for a name to print. std::string is the standard library’s type for text, from <string>.

  • virtual ~Potential() = default; the destructor, the function that runs when an object is removed, named with a ~. Making it virtual ensures that removing a plug through a Potential pointer runs the right plug’s cleanup. = default asks the compiler to write the usual one.

A class with a pure virtual function is abstract: you cannot make an object of it, because some of its functions do not exist. You can only make objects of classes that supply them all.

Two plugs#

Listing 20 plug.cpp (plug 1)#
15// Plug 1: Lennard-Jones.
16class LJPotential : public Potential {
17public:
18    LJPotential(double epsilon, double sigma, double cutoff) {
19        epsilon_ = epsilon;
20        sigma_ = sigma;
21        cutoff_ = cutoff;
22    }
23    double energy(double r) const override {
24        if (r > cutoff_) {
25            return 0.0;
26        }
27        double sr6 = std::pow(sigma_ / r, 6);
28        return 4.0 * epsilon_ * (sr6 * sr6 - sr6);
29    }
30    std::string name() const override { return "Lennard-Jones"; }
31
32private:
33    double epsilon_;
34    double sigma_;
35    double cutoff_;
36};

This is the LJPotential of Classes, with two changes:

  • : public Potential on line 16 makes LJPotential inherit from Potential: an LJPotential is a kind of Potential, and anything that can hold a Potential can hold an LJPotential.

  • override on lines 23 and 30 says “this supplies one of the socket’s functions”. It is a check: if the function does not match one in Potential exactly, the compiler stops (below).

The second plug is a soft repulsion, a simple energy function used in coarse models: \(U(r) = A\,(1 - r/r_c)^2\) for \(r < r_c\), and 0 beyond. It pushes overlapping particles apart and has no attraction.

Listing 21 plug.cpp (plug 2)#
38// Plug 2: a soft repulsion, A (1 - r/rc)^2 inside rc, zero outside.
39class SoftRepulsion : public Potential {
40public:
41    SoftRepulsion(double strength, double range) {
42        strength_ = strength;
43        range_ = range;
44    }
45    double energy(double r) const override {
46        if (r > range_) {
47            return 0.0;
48        }
49        double x = 1.0 - r / range_;
50        return strength_ * x * x;
51    }
52    std::string name() const override { return "soft repulsion"; }
53
54private:
55    double strength_;
56    double range_;
57};

Its data members differ from LJPotential’s, and its formula differs, but it supplies the same two functions with the same parameters, so it fits the same socket.

The force step: a list of plugs#

Listing 22 plug.cpp (the force step)#
59// The force step: holds any number of plugs and adds them up.
60class ForceCalculator {
61public:
62    void addPotential(std::shared_ptr<Potential> potential) {
63        potentials_.push_back(potential);
64    }
65    double energy(double r) const {
66        double total = 0.0;
67        for (const std::shared_ptr<Potential>& p : potentials_) {
68            total += p->energy(r);
69        }
70        return total;
71    }
72    void describe() const {
73        for (const std::shared_ptr<Potential>& p : potentials_) {
74            std::cout << "  plug: " << p->name() << "\n";
75        }
76    }
77
78private:
79    std::vector<std::shared_ptr<Potential>> potentials_;
80};

ForceCalculator keeps its plugs in potentials_, a vector of std::shared_ptr<Potential> (line 79). A pointer holds the address of an object, chapter 1’s &r, kept in a variable. std::shared_ptr, from <memory>, is the standard library’s pointer that also looks after the object: the object stays alive as long as some shared_ptr points to it, and is removed when the last one goes away. p->energy(r) on line 68 calls energy on the object that p points to; -> is the . of chapter 3 for a pointer.

energy (lines 65–71) only knows that each plug is some Potential. It calls p->energy(r) on each and adds the results. It never names LJPotential or SoftRepulsion, so a third plug written next year would fit without changing a line of ForceCalculator.

Listing 23 plug.cpp (main)#
82int main() {
83    ForceCalculator calculator;
84    calculator.addPotential(std::make_shared<LJPotential>(1.0, 1.0, 2.5));
85    std::cout << "LJ only:          U(0.95) = " << calculator.energy(0.95)
86              << ", U(1.5) = " << calculator.energy(1.5) << "\n";
87
88    calculator.addPotential(std::make_shared<SoftRepulsion>(10.0, 1.0));
89    calculator.describe();
90    std::cout << "LJ + soft:        U(0.95) = " << calculator.energy(0.95)
91              << ", U(1.5) = " << calculator.energy(1.5) << "\n";
92    return 0;
93}

std::make_shared<LJPotential>(1.0, 1.0, 2.5) makes an LJPotential with those constructor arguments and returns a shared_ptr to it; passing it to addPotential plugs it in.

$ clang++ -std=c++17 plug.cpp -o plug
$ ./plug
LJ only:          U(0.95) = 1.96097, U(1.5) = -0.320337
  plug: Lennard-Jones
  plug: soft repulsion
LJ + soft:        U(0.95) = 1.98597, U(1.5) = -0.320337

At 0.95σ the soft repulsion adds \(10 \times (1 - 0.95)^2 = 0.025\) to the LJ energy; at 1.5σ it is beyond its range of 1.0 and adds nothing. The same call, calculator.energy(r), gave both results; only the list of plugs changed.

How the right formula is found#

Line 68 is the same line for both plugs, yet it runs the LJ formula for one and the soft-repulsion formula for the other. The compiler arranges this with one hidden member (Fig. 18). For every class with virtual functions it writes a table of that class’s versions of them. Every object of such a class holds, as a hidden first member, a pointer to its class’s table. p->energy(r) follows the object’s table pointer and runs the energy it finds there. This is virtual dispatch.

../_images/cpp5_dispatch.svg

Fig. 18 The force step’s list holds pointers to objects of different classes. Each object carries a hidden pointer to its class’s table of functions, and p->energy(r) runs the version in that table.#

The hidden member is visible in the object’s size. This program compares an LJ struct with the same three doubles and no virtual functions against the LJPotential plug:

$ ./sizes
PlainLJ (no virtual functions): 24 bytes
LJPotential (plugs into Potential): 32 bytes

Three doubles are 24 bytes; the plug carries 8 more, the table pointer. (The C++ standard does not say how virtual dispatch must work; this table scheme is what clang, GCC and Microsoft’s compiler all use.)

If you know Python

Python finds every method this way: p.energy(r) looks up energy on the object’s class when the line runs, and any object with an energy method works. C++ looks up at run time only functions marked virtual, and only classes that inherit from Potential fit a shared_ptr<Potential>; the compiler checks both before the program runs.

Why the list holds pointers#

The list holds pointers, not the plugs themselves. Holding a Potential directly is not possible, because Potential is abstract:

    LJPotential lj(1.0, 1.0, 2.5);
    Potential copy = lj;
$ clang++ -std=c++17 by_value.cpp -o by_value
by_value.cpp:61:15: error: variable type 'Potential' is an abstract class
   61 |     Potential copy = lj;
      |               ^
by_value.cpp:11:20: note: unimplemented pure virtual method 'energy' in 'Potential'
   11 |     virtual double energy(double r) const = 0;
      |                    ^
by_value.cpp:12:25: note: unimplemented pure virtual method 'name' in 'Potential'
   12 |     virtual std::string name() const = 0;
      |                         ^
1 error generated.

A variable of type Potential would have room only for a Potential’s members, not for an LJPotential’s ε, σ and cutoff, nor a SoftRepulsion’s. A pointer is the same size whatever it points to, so a vector of pointers can hold plugs of every kind side by side.

override catches mistakes#

override makes the compiler check that a function really plugs into the socket. In this version, plug 2’s energy lost its const:

    double energy(double r) override {
$ clang++ -std=c++17 override_typo.cpp -o override_typo
override_typo.cpp:45:29: error: non-virtual member function marked 'override' hides virtual member function
   45 |     double energy(double r) override {
      |                             ^
override_typo.cpp:11:20: note: hidden overloaded virtual function 'Potential::energy' declared here: different qualifiers ('const' vs unqualified)
   11 |     virtual double energy(double r) const = 0;
      |                    ^
1 error generated.

Without override, the same mistake still fails, but far from the cause: this energy becomes a separate function that does not fill the socket, SoftRepulsion stays abstract, and the error appears inside the standard library’s shared_ptr code, where make_shared tries to make the object:

.../c++/v1/__memory/compressed_pair.h:66:7: error: field type 'SoftRepulsion' is an abstract class

With override, the error is on the line that is wrong, and the note names the line in the socket it fails to match.

Where the engine uses it#

The engine’s socket is Potential, declared next to ForceCalculator. Its pure virtual functions are the two questions of A simple molecular dynamics loop:

  • calculateEnergy(const Geometry& geometry), the total energy of all atoms;

  • calculateForces(const Geometry& geometry, std::vector<std::array<double, 3>>& forces), the force on every atom;

plus getName() and a virtual destructor. A third function, calculateForcesAndEnergy, is virtual but not pure: it has a default body that calls the other two, and LJPotential replaces it to get both from one pass over the pairs. LJPotential and DFTPotential both inherit from it with : public Potential and mark their versions override. ForceCalculator keeps its plugs in a std::vector<std::shared_ptr<Potential>>, adds them with addPotential, and adds up their energies and forces in a loop, as here. The engine’s functions take a whole Geometry rather than one distance, because one call computes every pair.

Check yourself#

1. What would make LJPotential abstract again?

Removing (or misspelling, without override) its version of any pure virtual function of Potential, for example name(). Then make_shared<LJPotential> would fail to compile, as Potential copy = lj; did.

2. You write a third plug, HarmonicBond, inheriting from Potential. Which lines of ForceCalculator change?

None. ForceCalculator only calls energy and name through Potential pointers; plugging in the new class takes one addPotential call in main.

3. Why is LJPotential 32 bytes when its three members take 24?

Because it has virtual functions: every object holds a hidden 8-byte pointer to its class’s table of functions, which p->energy(r) follows.

4. What does calculator.energy(0.5) return once both plugs are in?

The sum of both plugs at r = 0.5: the LJ energy, \(4[(1/0.5)^{12} - (1/0.5)^{6}] = 16128\), plus the soft repulsion, \(10 \times (1 - 0.5)^2 = 2.5\), so 16130.5. At half of σ the LJ wall dwarfs everything else.

Next#

plug.cpp is one file of 93 lines, and the engine’s src/ folder holds about 4,600. The next chapter, Several files, splits a program across several files, the way the engine is organised: declarations in headers, code in source files, joined by the linker.