Object-oriented scientific programming with C++¶

Matthias Möller, Jonas Thies (Numerical Analysis, DIAM)

Lecture 2 - 18 November 2026

Learning objectives of this lecture¶

  • Grouping of data and functionality into classes
  • Controlling visibility of class members
  • Creating and releasing objects from classes
  • Overloading functions and operators
  • Using data containers from the C++ standard library

Block A: Building a Polynomial class¶

A real-valued polynomial of degree $n$ can be written as $$ p(x)=C_0 + C_1 x + C_2 x^2 + \dots + C_n x^n $$ with $n+1$ coefficients $C_i\in \mathbb{R}$.

Task: Develop a C++ program that supports creation, evaluation, and destruction of polygons and bundles the functionality in a so-called class.

In block A we explicitly want to handle data and memory allocation ourselves, that is, we do not make sense of any container functionality from the C++ standard library. That comes in block B.

Step A.1: Create an array polynomial evaluator¶

Prompt: Create a C++ program defining a simple function evaluate_polynomial that evaluates a polynomial, given its coefficients and its degree. Then in main create a static array with the coefficients {1, 2, 3} of a polynomial of degree 2 and use the created function to evaluate it at x=2. Print the result. Document the code with short comments.

// Evaluates p(x) = c[0] + c[1] x + ... + c[degree] x^degree.
// The array must hold degree + 1 coefficients (increasing powers).
double evaluate_polynomial(const double* coefficients, int degree, double x)
{
    double result = 0.0;
    double power = 1.0; // current power x^i, starting with x^0 = 1

    for (int i = 0; i <= degree; ++i)
    {
        result += coefficients[i] * power;
        power *= x;
    }

    return result;
}
int main()
{
    // p(x) = 1 + 2x + 3x^2 has degree 2, so it needs 3 coefficients
    const int degree = 2;
    double coefficients[degree + 1] = {1, 2, 3};

    double result = evaluate_polynomial(coefficients, degree, 2.0);

    std::cout << result << std::endl;

    return 0;
}

Recap from previous week¶

double coefficients[degree + 1] = {1, 2, 3};

creates a fixed-size array of double values. That's why degree must be const.

double evaluate_polynomial(const double* coefficients, int degree, double x) { ... }

passes the array by pointer together with its degree and the location where to evaluate it.

What can go wrong here?¶

User (un-)intentionally mixes up dimensions:

const int degree = 2;
double coefficients[degree] = {1, 2};
double result = evaluate_polynomial(coefficients, degree, 2.0);
const int degree = 2;
double coefficients[degree + 2] = {1, 2, 3, 4};
double result = evaluate_polynomial(coefficients, degree, 2.0);

Quiz:

  • Which of the two is more dangerous?
  • Which of the two is more difficult to find?

Step A.2: Bundle the polynomial data in a struct¶

Prompt: Replace the separate coefficient pointer and degree variables with a struct called Polynomial}. The struct should store a pointer to the coefficients and the degree. Keep ``evaluate_polynomial as a standalone function for now, but pass it a Polynomial object. Make sure that a Polynomial object can be created by a constructor that takes the coefficients array and the degree as arguments.

// A polynomial of given degree, with degree + 1 coefficients.
struct Polynomial
{
    const double* coefficients; // in increasing powers of x
    int degree;                 // highest power of x

    // Creates a polynomial from a coefficient array and its degree.
    Polynomial(const double* coefficients, int degree)
        : coefficients(coefficients), degree(degree) {}
};
// Evaluates the polynomial at the point x.
double evaluate_polynomial(const Polynomial& polynomial, double x)
{
    double result = 0.0;
    double power = 1.0; // current power x^i

    for (int i = 0; i <= polynomial.degree; ++i)
    {
        result += polynomial.coefficients[i] * power;
        power *= x;
    }

    return result;
}
int main()
{
    // p(x) = 1 + 2x + 3x^2
    double coefficients[] = {1, 2, 3};

    Polynomial polynomial(coefficients, 2);

    double result = evaluate_polynomial(polynomial, 2.0);

    std::cout << result << std::endl;

    return 0;
}

Structures¶

Syntax:

struct name 
{
    // Attributes and functions go here
};

defines a structure with the name name. It must be terminated with ;.

All attributes and functions bundled into the structure must be implemented between { and };.

Example:

struct Polynomial
{
    const double* coefficients; // in increasing powers of x
    int degree;                 // highest power of x
};

Constant coefficients and variable degree are attributes of the structure Polynimoal.

You can say that, Polynomial owns them. Any additional functionality inside the structure can access them.

Constructors¶

Example:

struct Polynomial
{
    // Creates a polynomial from a coefficient array and its degree.
    Polynomial(const double* coefficients, int degree)
        : coefficients(coefficients), degree(degree) {}
};

int main()
{
    double coefficients[] = {1, 2, 3};
    Polynomial polynomial(coefficients, 2);
}

Constructors are special functions with the same name as the structure that allow to create objects or instances of the structure.

Let's have a closer look at the constructor

Polynomial(const double* coefficients, int degree)
        : coefficients(coefficients), degree(degree) {}

The body {} is actually empty. So where does the work happen?

':' is a special mechanism, called delegation.

Instead of implementing functionality in the constructor's body, the constructor delegates the initialization of the variable coefficients and the constant degree.

Did you notice that the name of the structures's attributes and constructor's parameters are the same?

Now that we have a living object

double coefficients[] = {1, 2, 3};
Polynomial polynomial(coefficients, 2);

we can access its attributes as follows

for (int i = 0; i <= polynomial.degree; ++i)
    {
        result += polynomial.coefficients[i] * power;
        power *= x;
    }

Quiz: Can we integrate the functionality of evaluate_polynomial inside the structure?

Step A.3: Turn evaluation into a member function¶

Prompt: Move evaluate_polynomial into the Polynomial struct as a member function called evaluate. Keep the coefficients and degree public for now. The main function should call polynomial.evaluate(2.0).

// A polynomial of given degree, with degree + 1 coefficients.
struct Polynomial
{
    // Evaluates the polynomial at the point x.
    double evaluate(double x) const
    {
        double result = 0.0;
        double power = 1.0; // current power x^i

        for (int i = 0; i <= degree; ++i)
        {
            result += coefficients[i] * power;
            power *= x;
        }

        return result;
    }
};
int main()
{
    // p(x) = 1 + 2x + 3x^2
    double coefficients[] = {1, 2, 3};

    Polynomial polynomial(coefficients, 2);

    double result = polynomial.evaluate(2.0);

    std::cout << result << std::endl;

    return 0;
}

Step A.4: Make the attributes private¶

Prompt: Make coefficients and degree private attributes of Polynomial, so that only the class itself can access them. Keep the constructor and evaluate public. Since most of our type is now hidden, use the keyword class instead of struct.

class Polynomial
{
private:
    const double* coefficients; // in increasing powers of x
    int degree;                 // highest power of x

public:
    // Creates a polynomial from a coefficient array and its degree.
    Polynomial(const double* coefficients, int degree)
        : coefficients(coefficients), degree(degree)
    {}

    // Evaluates the polynomial at the point x.
    double evaluate(double x) const { ... }
};

Classes and structures¶

The two types class and struct are not too different.

class defines everything as private by default.

struct defines everything as public by default.

Step A.5: Own the coefficients and add a destructor¶

Prompt: Change the constructor of Polynomial so that the object stores its own copy of the coefficients in a dynamically allocated array, instead of pointing to the array of the caller. Add a destructor that releases this array. Show in main that changing the original array no longer changes the polynomial, and that the destructor is called automatically when the object goes out of scope.

// A polynomial that owns a copy of its degree + 1 coefficients.
class Polynomial
{
public:
    // Creates a polynomial with its own copy of the coefficients.
    Polynomial(const double* coefficients, int degree)
        : coefficients(new double[degree + 1]), degree(degree)
    {
        for (int i = 0; i <= degree; ++i)
        {
            this->coefficients[i] = coefficients[i];
        }
    }

    // Releases the coefficient array when the object is destroyed.
    ~Polynomial()
    {
        delete[] coefficients;
        std::cout << "Destructor called" << std::endl;
    }
};
int main()
{
    // p(x) = 1 + 2x + 3x^2
    double coefficients[] = {1, 2, 3};
    {
        Polynomial polynomial(coefficients, 2);

        // Changing the array no longer changes the polynomial
        coefficients[0] = 100;
    
        std::cout << polynomial.evaluate(2.0) << std::endl;
    }

    std::cout << "Polynomial is out of scope" << std::endl;
    
    return 0;
}

Dynamic memory¶

Syntax:

type* name = new type[size]

allocates an array dynamically and returns a pointer to its first element. The size can be determined at runtime.

Example:

double* coefficients = new double[degree + 1];

Dynamic memory continued¶

Syntax:

delete[] name

releases an array previously allocated with new[]. For class types, each element’s destructor is called before the memory is released.

Be aware that you are responsible for calling delete[] for all dynamically allocated memory. Always! In all non-standard situations such as early exists with exceptions. We will see a smarter pointer approach later in this course.

The this pointer¶

Syntax:

this->member_name

Inside a non-static member function, this points to the object on which the function was called.

Example:

Polynomial(const double* coefficients, int degree)
        : coefficients(new double[degree + 1]), degree(degree)
    {
        for (int i = 0; i <= degree; ++i)
        {
            this->coefficients[i] = coefficients[i];
        }
    }

Destructors¶

Syntax:

class name 
{
    ~name() {}
};

Each class and struct can have one destructor.

It does not take any parameters and is automatically called when the object goes out of scope.

The body implements what should be done to 'clean up' the object.

Step A.6: Construct a polynomial from a coefficient list¶

Prompt: Add an initializer list constructor so that I can write Polynomial p = {3.0, 2.0, -5.0}. The list entries are the coefficients in increasing powers of x, and the degree should follow from the number of entries. The constructor should copy the coefficients into the object owned dynamic array. Keep the existing constructor, and show in main that both can be used.

#include <initializer_list>

// A polynomial that owns a copy of its degree + 1 coefficients.
class Polynomial
{
public:
    // Creates a polynomial from a list, e.g. {3.0, 2.0, -5.0}.
    // The degree follows from the number of coefficients.
    Polynomial(std::initializer_list<double> coefficient_list)
        : coefficients(new double[coefficient_list.size()]),
          degree(static_cast<int>(coefficient_list.size()) - 1)
    {
        int i = 0;
        for (double coefficient : coefficient_list)
        {
            coefficients[i] = coefficient;
            ++i;
        }
    }
};
int main()
{
    double coefficients[] = {1, 2, 3};

    {
        // The compiler picks the constructor whose parameter list
        // matches the arguments
        Polynomial q(coefficients, 2);   // q(x) = 1 + 2x + 3x^2
        Polynomial p = {3.0, 2.0, -5.0}; // p(x) = 3 + 2x - 5x^2

        std::cout << q.evaluate(2.0) << std::endl;
        std::cout << p.evaluate(2.0) << std::endl;
    } // p and q go out of scope here

    std::cout << "Polynomials are out of scope" << std::endl;

    return 0;
}

Initializer lists¶

Syntax:

std::initializer_list<type> name

provides access to a sequence of values of the same type, written in braces {}.

Its size can be retrieved by the size() member function.

Example:

#include <initializer_list>

std::initializer_list<double> coefficient_list = {1, 2, 3};
std::size_t degree = coefficient_list.size() - 1;

Casting between types¶

Syntax:

static_cast<target_type>(expression)

explicitly converts a value from one type to another. The compiler checks whether the conversion is permitted.

Example:

degree(static_cast<int>(coefficient_list.size()) - 1)

All containers from the C++ standard library return their size as std::size_t type. Here, we cast it to int.

Range based for-loops¶

Syntax:

for (type name : range) { body }

visits each element in range and makes it accessible inside the body

Example:

int i = 0;
for (double coefficient : coefficient_list) { 
    coefficients[i] = coefficient;
    ++i;
}

Step A.7: Make copying and assignment safe¶

Prompt: I want to be able to create a Polynomial object that is a copy of an already existing one. I also want to be able to change a Polynomial object by assigning another one to it, making them equal copies.

class Polynomial
{
    // Copy constructor: the new polynomial gets its own copy of the
    // coefficients of other (deep copy).
    Polynomial(const Polynomial& other)
        : coefficients(new double[other.degree + 1]), degree(other.degree) 
    {
        for (int i = 0; i <= degree; ++i)
        {
            coefficients[i] = other.coefficients[i];
        }
    }
};
class Polynomial
{
    // Copy assignment: replaces the coefficients of this 
    // polynomial by a copy of the coefficients of other.
    Polynomial& operator=(const Polynomial& other)
    {
        if (this != &other) // skip self-assignment (p = p)
        {
            delete[] coefficients;
            degree = other.degree;
            coefficients = new double[degree + 1];

            for (int i = 0; i <= degree; ++i)
            {
                coefficients[i] = other.coefficients[i];
            }
        }

        return *this;
    }
};
int main()
{
    Polynomial p = {3.0, 2.0, -5.0};

    Polynomial q(p); // copy constructor: q is a new copy of p

    Polynomial r = {1.0};
    r = p;           // copy assignment: r becomes a copy of p

    std::cout << p.evaluate(2.0) << std::endl;
    std::cout << q.evaluate(2.0) << std::endl;
    std::cout << r.evaluate(2.0) << std::endl;

    return 0;
}

Copy constructors¶

Syntax:

class name
{
    name(const name& other) { ... }
};

creates a new object of the class or structure by copying the data from other.

Note that you are responsible for how data is copied. In our example, we make a deep copy of the coefficients.

Copy assignment operators¶

Syntax:

type& operator=(const type& other) { ... }

assigns a copy of other to the current object. Before, it needs to delete the current's objects internal data.

Quiz: Is there a way to move the data from other into the current object without making a (deep) copy?

class Polynomial
{
    Polynomial(Polynomial&& other)
        : degree(other.degree), coefficients(other.coefficients) {
        other.coefficients = nullptr;
        // changing the other to nullptr prevents it from being used after the move
    }

    Polynomial& operator=(Polynomial&& other) {
        degree = other.degree;
        coefficients = other.coefficients;
        other.coefficients = nullptr;
        return *this;
    }

Move constructors and assignment operators¶

Syntax:

name(name&& other) { ... }

type& operator=(type&& other) { ... }

The && indicates that the attributes from other can be moved into the current object.

After the data has been moved, it is no longer available from other. To prevent pointer hazards it is recommended to set other's pointers to nullptr.

Step A.8: Create monomials through a class-level factory function¶

Prompt: Add a function that allows me to create a Polynomial object that is a monomial by passing its degree and coefficient. Also add one that creates a Polynomial object that is just a constant value. I want to use these functions so that I can quickly create Polynomial objects that are monomials or constants. To build them, add a private constructor that creates a polynomial of a given degree with all coefficients equal to zero.

class Polynomial
{
    // Factory function : creates the monomial coefficient * x^degree.
    static Polynomial monomial(int degree, double coefficient)
    {
        Polynomial result(degree); // all coefficients zero
        result.coefficients[degree] = coefficient;
        return result;
    }

    // Factory function: creates the constant polynomial p(x) = value.
    static Polynomial constant(double value)
    {
        Polynomial result(0);
        result.coefficients[0] = value;
        return result;
    }
};
int main()
{
    Polynomial p = Polynomial::monomial(2, -5.0); // p(x) = -5x^2
    Polynomial q = Polynomial::constant(3.0);     // q(x) = 3

    std::cout << p.evaluate(2.0) << std::endl;
    std::cout << q.evaluate(2.0) << std::endl;

    return 0;
}

Static functions¶

Syntax:

class class_name {
    static type function_name(...) { ... }
};

Static functions of a class or structure can be called without creating an object.

class_name::function_name(...);

Factory functions¶

A common practice in C++ is to use factory functions as quick way to instantiate objects.

Example:

static Polynomial constant(double value) { ... }

creates a regular Polynomial object, but it takes care of setting the coefficients in a way that the polynomial represents a constant, i.e., $ p(x) = \text{value} $.

Step A.9: Enable mathematical operations between Polynomial objects¶

Prompt: Extend the Polynomial class with operator() for evaluation, operator+= for in-place addition, operator+ for polynomial addition, and operator* for polynomial multiplication. Use const correctness: operations that do not modify the current object should be marked const, and input polynomials should be passed by const reference.

class Polynomial
{
public:
    // Makes the polynomial callable: p(x) evaluates p at x.
    double operator()(double x) const
    {
        return evaluate(x);
    }
};

Function call operator¶

Syntax:

class class_name {
    result_type operator(input_type inpute_name) const { ... }
};

allows you to call

object(argument) // Equivalent to object.operator()(argument)

An object with operator() is called a function object or functor.

class Polynomial
{
public:
    // Returns this + other, without changing either.
    Polynomial operator+(const Polynomial& other) const
    {
        Polynomial result(*this);
        result += other;

        return result;
    }
};
class Polynomial
{
public:   
    // Adds other to this polynomial (in place).
    Polynomial& operator+=(const Polynomial& other)
    {
        int new_degree = degree;

        if (other.degree > new_degree) { new_degree = other.degree; }

        double* new_coefficients = new double[new_degree + 1];

        for (int i = 0; i <= new_degree; ++i)
        {
            new_coefficients[i] = 0.0;
            if (i <= degree) { new_coefficients[i] += coefficients[i]; }
            if (i <= other.degree) { new_coefficients[i] += other.coefficients[i]; }
        }

        delete[] coefficients;

        coefficients = new_coefficients;
        degree       = new_degree;

        return *this;
    }
};

Quiz¶

What are the semantical and technical differences between

Polynomial operator+(const Polynomial& other) const

and

Polynomial& operator+=(const Polynomial& other)
class Polynomial
{
public:
    // Returns this * other, without changing either.
    Polynomial operator*(const Polynomial& other) const
    {
        Polynomial result(degree + other.degree); // all zero

        for (int i = 0; i <= degree; ++i)
        {
            for (int j = 0; j <= other.degree; ++j)
            {
                result.coefficients[i + j] +=
                    coefficients[i] * other.coefficients[j];
            }
        }

        return result;
    }
};
int main()
{
    Polynomial p = {3.0, 2.0, -5.0};             // 3 + 2x - 5x^2
    Polynomial q = Polynomial::monomial(1, 4.0); // 4x
    Polynomial r = Polynomial::constant(7.0);    // 7

    Polynomial sum = p + q;
    Polynomial product = p * q;
    r += p;

    std::cout << p(2.0) << std::endl;
    std::cout << sum(2.0) << std::endl;
    std::cout << product(2.0) << std::endl;
    std::cout << r(2.0) << std::endl;

    return 0;
}

What did we learn so far?¶

  • Grouping of data and functionality into classes and structures
  • Controlling visibility of class members with private and public
  • Creating and releasing objects from classes with constructors and destructors
  • Overloading functions and operators

What we have not yet touched is the last learning goal:

  • Using data containers from the C++ standard library

Block B: Standard containers for the Polynomial¶

In the previous block we developed a Polynomial class that implements all functionality explicitly, e.g., arrays are allocated and destroyed dynamically withnew[] and delete[], respectively.

The C++ standard library provides handy containers for keeping collections of data such as arrays. In this block we will rewrite the Polynomial class to use std::vector and std::array.

Step B.1: Let a vector own the coefficients¶

Prompt: Replace the dynamically allocated coefficient array of Polynomial with a std::vector<double>, and remove everything that is no longer needed now that the vector manages the memory. A vector knows its own size, so do not store the degree separately: compute it in a member function degree(). In main, show that copying a polynomial still gives an independent copy.

#include <initializer_list>
#include <iostream>
#include <vector>
// A polynomial whose coefficients are stored in a std::vector.
class Polynomial
{
private:
    // Coefficients in increasing powers of x, owned by the vector
    std::vector<double> coefficients;

    // Private helper constructor: all coefficients set to zero.
    Polynomial(int degree) 
        : coefficients(degree + 1, 0.0) {}

public:
    // Creates a polynomial with its own copy of the coefficients.
    Polynomial(const double* coefficients, int degree)
        : coefficients(coefficients, coefficients + degree + 1) {}

    // Creates a polynomial from a list, e.g. {3.0, 2.0, -5.0}.
    Polynomial(std::initializer_list<double> coefficient_list)
        : coefficients(coefficient_list) {}

    // Returns the degree: the number of coefficients minus one.
    int degree() const {
        return static_cast<int>(coefficients.size()) - 1;
    }

    // Evaluates the polynomial at point x
    double evaluate(double x) const {
        double result = 0.0;
        double power = 1.0; // current power x^i

        for (int i=0; i <= degree(); i++) {
            result += coefficients[i] * power;
            power *= x;
        }

        return result;
    }

    // Adds two polynomials in place
    Polynomial& operator+=(const Polynomial& other) {
        int new_degree = (degree() > other.degree()) ? degree() : other.degree();

        //new vector of zeros, long enough for both polynomials
        std::vector<double> new_coefficients(new_degree + 1, 0.0);

        for (int i=0; i <= new_degree; i++) {
            if (i <= degree()) new_coefficients[i] += coefficients[i];

            if (i <= other.degree()) new_coefficients[i] += other.coefficients[i];
        }

        coefficients = new_coefficients;

        return *this;
    }
};
int main()
{
    Polynomial p = {3.0, 2.0, -5.0}; // 3 + 2x - 5x^2

    Polynomial q = p; // copy made by the generated copy constructor
    q += Polynomial::constant(1.0);

    std::cout << p(2.0) << std::endl;
    std::cout << q(2.0) << std::endl;
    std::cout << q.degree() << std::endl;

    return 0;
}

Container class: std::vector¶

Syntax:

std::vector<type> name

is a dynamic-size container for contiguously stored data.

It can be easily constructed from an initializer_list object.

Its size can be retrieved by size().

Individual elements can be accessed by object[i].

It also supports range-based for-loops.

Step B.2: Keep the degree correct¶

Prompt: Add a member function print that shows the coefficients and the degree of a polynomial. Make sure that the degree is always correct, also when terms cancel and the result is the zero polynomial, and that multiplying by the zero polynomial gives the zero polynomial.

class Polynomial {
private:
    // Removes zeros at the end of the coefficients, so that the last 
    // coefficient is never zero and degree() is correct.
    void remove_trailing_zeros() {
        while (!coefficients.empty() && coefficients.back() == 0.0) {
            coefficients.pop_back();
        }
    }
};

Container class: std::vector continued¶

std::vector provides functions to query, access, and remove elements:

  • empty() returns true if the vector contains no elements.
  • size() returns the number of elements.
  • front() returns a reference to the first element.
  • back() returns a reference to the last element.
  • pop_front() removes the first| element and returns nothing.
  • pop_back() removes the last element and returns nothing.
class Polynomial {
public:
    // Creates a polynomial with its own copy of the coefficients.
    Polynomial(const double* coefficients, int degree)
        : coefficients(coefficients, coefficients + degree + 1) 
    {
        remove_trailing_zeros();
    }

    // Creates a polynomial from a list, e.g. {3.0, 2.0, -5.0}.
    Polynomial(std::initializer_list<double> coefficient_list)
        : coefficients(coefficient_list) 
    {
        remove_trailing_zeros();
    }
};
class Polynomial {
public:
    // Factory function: creates the monomial coefficient * x^degree.
    static Polynomial monomial(int degree, double coefficient) {
        Polynomial result(degree); // all coefficients zero
        result.coefficients[degree] = coefficient;
        result.remove_trailing_zeros(); // coefficient may be zero
        return result;
    }

    // Factory function: creates the constant polynomial p(x) = value.
    static Polynomial constant(double value) {
        Polynomial result(0);
        result.coefficients[0] = value;
        result.remove_trailing_zeros(); // value may be zero
        return result;
    }
};
class Polynomial {
public:
    // Prints the coefficients followed by the degree.
    void print() const {
        for (double coefficient : coefficients) {
            std::cout << coefficient << " ";
        }
        std::cout << "(degree " << degree() << ")" << std::endl;
    }
};
class Polynomial {
public:
    // Add two polynomials in place
    Polynomial& operator+=(const Polynomial& other) {
        int new_degree = (degree() > other.degree()) ? degree() : other.degree();

        //new vector of zeros, long enough for both polynomials
        std::vector<double> new_coefficients(new_degree + 1, 0.0);

        for (int i=0; i <= new_degree; i++) {
            if (i <= degree()) new_coefficients[i] += coefficients[i];

            if (i <= other.degree()) new_coefficients[i] += other.coefficients[i];
        }

        coefficients = new_coefficients;
        remove_trailing_zeros(); // terms may cancel

        return *this;
    }
};
int main()
{
    Polynomial p = {3.0, 2.0, -5.0}; // 3 + 2x - 5x^2
    Polynomial minus_p = p * Polynomial::constant(-1.0);

    Polynomial zero = p + minus_p;
    Polynomial product = zero * p;

    p.print();
    minus_p.print();
    zero.print();
    product.print();

    return 0;
}

Step B.3: Differentiate, compare and read coefficients¶

Prompt: Add a member function derivative that returns the derivative as a new polynomial, building its coefficients one at a time with push_back. Add a way to check whether two polynomials are equal, and a member function coefficient that returns one coefficient and reports an error for an index that does not exist. In main, check the derivative of $1 + 2x^3$ against $6x^2$ and ask for a coefficient that does not exist.

#include <stdexcept>

class Polynomial
{
public:
    // Returns the coefficient of x^index. Throws std::out_of_range
    // if the polynomial has no such coefficient.
    double coefficient(int index) const {
        return coefficients.at(index);
    }

    // Returns the derivative as a new polynomial.
    Polynomial derivative() const {
        Polynomial result = {}; // starts as the zero polynomial

        for (int i = 1; i <= degree(); ++i) {
            result.coefficients.push_back(i * coefficients[i]);
        }

        return result;
    }

    // Two polynomials are equal when all coefficients are equal.
    bool operator==(const Polynomial& other) const {
        return coefficients == other.coefficients;
    }
};
int main()
{
    Polynomial p = {1.0, 0.0, 0.0, 2.0}; // 1 + 2x^3
    Polynomial dp = p.derivative();
    Polynomial expected = Polynomial::monomial(2, 6.0); // 6x^2

    dp.print();

    if (dp == expected) std::cout << "The derivative is correct" << std::endl;

    std::cout << p.coefficient(3) << std::endl;

    try {
        std::cout << p.coefficient(10) << std::endl;
    }
    catch (const std::out_of_range& e) {
        std::cerr << "Out of range: " << e.what() << std::endl;
    }

    return 0;
}

Container class: std::vector continued¶

std::vector provides functions to append elements to its back:

  • push_back(value) adds an element to the end of the vector.

It does not provide a push_front function, but this can be mitigated by:

object.insert(object.begin(), value)

Step B.4: Check the derivative at fixed points¶

Prompt: Write a free function derivative_errors that compares derivative() with the central difference at five fixed points and returns the five absolute errors. Use std::array for the points and for the result. In main, test it on $1 + 2x^3$ at $x = -2, -1, 0, 1, 2$ with $h = 0.001$.

#include <array>
#include <cmath>

// Compares derivative() with the central difference
// (p(x + h) - p(x - h)) / (2h) at five points and returns the
// absolute errors.
std::array<double, 5> derivative_errors(const Polynomial& p, 
                                        const std::array<double, 5>& points, 
                                        double h) {
    Polynomial dp = p.derivative();
    std::array<double, 5> errors = {};

    for (std::size_t i = 0; i < points.size(); ++i) {
        double x = points[i];
        double numerical = (p(x + h) - p(x - h)) / (2.0 * h);
        errors[i] = std::abs(dp(x) - numerical);
    }

    return errors;
}
int main() {
    Polynomial p = {1.0, 0.0, 0.0, 2.0}; // 1 + 2x^3
    const std::array<double, 5> points = {-2.0, -1.0, 0.0, 1.0, 2.0};

    std::array<double, 5> errors = derivative_errors(p, points, 1e-3);

    for (std::size_t i = 0; i < errors.size(); ++i) {
        std::cout << "x = " << points[i] << "  error = " << errors[i] << std::endl;
    }
    return 0;
}

Container class: std:array¶

Syntax:

std::array<type, size> name

is a fixed-size container for contiguously stored data.

It provides some of the basic functionality as std::vector except for insertion, deletion of elements and resizing.

What did we learn in this lecture?¶

  • Grouping of data and functionality into classes and structures
  • Controlling visibility of class members with private and public
  • Creating and releasing objects from classes with constructors and destructors
  • Overloading functions and operators
  • Using std::array and std::vector containers from the C++ standard library