C++ Scientific Computing Fundamentals

Notes from the ARCHER2 C++ for Scientific Computing course, covering structs, constructors, and object-oriented programming in C++.

Structs

A struct is a class type whose members are public by default, used to group related data:

struct Complex {
    double re;
    double im;
};

A struct with no default values can be initialised inline:

Complex make_unit_complex() {
    return Complex(0.0, 1.0);
}

Setting default values for members disables inline initialisation:

struct Complex2 {
    double re = 0.0;
    double im = 0.0;
};
 
// This will not compile:
Complex2 make_unit_complex2() {
    return Complex2(0, 1);
}

Constructors

Use constructors to provide initialisation when default values are present:

struct Complex3 {
    Complex3() = default;
    Complex3(double re);
    Complex3(double re, double im);
 
    double re = 0.0;
    double im = 0.0;
};
 
Complex3::Complex3(double real) : re(real) {}
Complex3::Complex3(double real, double imag) : re(real), im(imag) {}

Constructor initialiser lists (: re(real), im(imag)) are more efficient than assignment inside the constructor body.

Object-Oriented Programming

Objects encapsulate data and member functions that operate on that data. Member functions can access and modify the object’s internal state:

struct Vector3 {
    double x, y, z;
 
    double magnitude() const {
        return std::sqrt(x * x + y * y + z * z);
    }
};

The const qualifier on a member function indicates it does not modify the object, enabling use on const instances.

References