Object-oriented scientific programming with C++¶
Matthias Möller, Jonas Thies
Lecture 3 - 25 November 2026
Learning objectives of this lecture¶
- Overloading of functions and operators
- Class inheritance
- Runtime polymorphism: virtual methods, override, and abstract classes
- Template meta-programming and specialization
- Automatic type deduction: auto
Block A: Overloading¶
We want to implement a C++ class Interval that represents a closed interval $I=[\text{low}, \text{high}]\subset \mathbb{R}$ and allows to check if
- a given point $x\in\mathbb{R}$ is inside or outside
- a given interval $J$ is fully contained in $I$ or not
While designing this class, we already keep in mind that we will afterwards extend it towards open intervals.
Step A.1: Creating an initial class Interval¶
Prompt: ???
We want to be able to run the following main function:
int main(){
Interval A{0, 5}, B{2,3};
std::cout << "A contains 3? " << A.contains(3.0) << std::endl;
std::cout << "B contains 4? " << B.contains(4.0) << std::endl;
std::cout << "A contains B? " << A.contains(B) << std::endl;
return 0;
}
Prompt: Make a C++ struct called Interval that stores a lower bound low and an upper bound high as
doubles, with a constructor taking both. Add a method contains(double x) that returns whether
x lies inside the closed interval. Then add another method contains(const Interval& other)
that returns whether the whole other interval lies inside this one. Also add a function that returns
the width of the interval. In main, build an interval $[0, 10]$, test a point inside, a point outside,
and a smaller interval inside.
#include <iostream>
struct Interval {
double high, low;
Interval(double low, double high): low(low), high(high) {}
bool contains(double x) const {
return (low <= x) && (x <= high);
}
bool contains(const Interval& other) const {
return (low <= other.low) && (other.high <= high);
}
double width() const {
return high - low;
}
};
int main(){
Interval A{0, 5}, B{2,3};
std::cout << "A contains 3? " << A.contains(3.0) << std::endl;
std::cout << "B contains 4? " << B.contains(4.0) << std::endl;
std::cout << "A contains B? " << A.contains(B) << std::endl;
return 0;
}
Why is this lecture block called 'Overloading'?¶
bool contains(double x) const { ... }
bool contains(const Interval& other) const { ... }
Overloading allows functions or operators with the same name to behave differently depending on the number or types of their arguments.
The return type does not distinguish overloads: two functions cannot differ solely in their return type. Any idea why?
Quiz: Who decides which contains function to call?¶
- Stand up if you think that the runtime system decides.
- Stay seated if you think that the compiler decides.
Correct answer: The compiler decides. This is why overloading is called compile-time polymorphism.
Quiz: Is this a valid overload?¶
int contains(double x) const {
if (x < low) return -1;
if (x > high) return 1;
else return 0;
}
No, because the only difference is in the return type.
Quiz: Is this a valid overload?¶
int contains(double y) const {
return (low <= y) && (y <= high);
}
No, because the compiler does not consider the parameter's name but only its type.
Quiz: Is this a valid overload?¶
bool contains(double x, double tol = 0.0) const {
return (low <= x + tol) && (x - tol <= high);
}
No, because the default parameter can be omitted and then it is not clear which overload to use.
Overloading¶
Overloading means defining multiple functions with the same name but different parameter lists in the same scope, such as a namespace, structure, or class. Functions cannot be overloaded solely by return type.
For each call, the compiler must be able to select a unique best-matching overload at compile time. Otherwise, it reports a compilation error.
Block B: Creating an OpenInterval class¶
We now want to implement the same functionality for an open interval $I=(\text{low}, \text{high})\subset \mathbb{R}$.
Think:
- Which parts of the existing implementation remain the same, and which need to change?
- How would you reuse the shared functionality while adapting the behavior that differs?
Prompt: ???
Step B.1: Creating a child class OpenInterval¶
Prompt: Create a new child class of Interval called OpenInterval. For now, simply add a constructor delegating to Interval's constructor. Create a new OpenInterval and try a few relevant values on it.
class OpenInterval : public Interval {
OpenInterval(double low, double high)
: Interval(low,high)
{}
};
int main() {
Interval A{0, 5};
std::cout << "A contains 3? " << A.contains(3.0) << std::endl;
std::cout << "B contains 4? " << B.contains(4.0) << std::endl;
OpenInterval B{2, 4};
std::cout << "width of B? " << B.width() << std::endl;
std::cout << "B contains 4? " << B.contains(4.0) << std::endl;
std::cout << "B contains A? " << B.contains(A) << std::endl;
return 0;
}
Inheritance¶
Syntax:
class DerivedClass : public BaseClass { ... };
DerivedClass inherits data members and member functions from BaseClass.
With public inheritance:
Public members of
BaseClassremain public inDerivedClass.Protected members of
BaseClassremain protected inDerivedClass.Private members of
BaseClasscannot be accessed directly byDerivedClass.
Visibility¶
class BaseClass
{
public:
int a;
protected:
int b;
private:
int c;
};
class DerivedClass
: public BaseClass
{};
- Public: accessible from outside the class.
- Protected: accessible within the class and its derived classes.
- Private: accessible only within the class itself.
Initializing the base class¶
So far, we have used member initializer lists to initialize data members such as double or int.
We can also use them to call a base-class constructor:
OpenInterval(double low, double high)
: Interval(low,high)
{}
The constructor of Interval runs before the body of the OpenInterval constructor.
Does class OpenInterval have the right functionality?¶
No, because it is essentially a new name for the Interval class.
We need to override the contains methods to enforce strict inequalities:
class OpenInterval : public Interval
{
bool contains (double x) const {
return (low < x) && (x < high );
}
bool contains (const Interval & other) const {
return (low < other.low) && (other.high < high);
}
};
Overloading vs. overriding¶
Overloading means defining multiple functions with the same name but different parameter lists in the same scope. Functions cannot be overloaded solely by return type.
Overriding means providing a new implementation of a member function from a base class in a derived class, with a matching signature.
Quiz¶
Interval A{0, 4};
OpenInterval B{0, 4};
Interval* p;
p = &A; // The &-operator gets the address of A
std::cout << p->contains(4) << std::endl;
p = &B; // The &-operator gets the address of B
std::cout << p->contains(4) << std::endl;
Think: what do you expect to see as output?
p = &A; // The &-operator gets the address of A (Interval)
std::cout << p->contains(4) << std::endl;
yields 1.
p = &B; // The &-operator gets the address of B (OpenInterval)
std::cout << p->contains(4) << std::endl;
yields 1.
The compiler selects the function based on the pointer’s declared type, regardless of the actual type of the object it points to.
This is called static binding.
Virtual functions¶
class Interval
{
virtual bool contains (double x) const {
return (low < x) && (x < high );
}
};
class OpenInterval : public Interval
{
bool contains (double x) const override {
return (low < x) && (x < high );
}
};
p = &A; // The &-operator gets the address of A (Interval)
std::cout << p->contains(4) << std::endl;
yields 1.
p = &B; // The &-operator gets the address of B (OpenInterval)
std::cout << p->contains(4) << std::endl;
yields 0.
Virtual functions¶
Syntax:
struct BaseClass {
virtual type name (...) { ... }
};
virtual enables runtime polymorphism: when called through a base-class pointer or reference, the function implementation is selected according to the object’s actual type.
Syntax:
struct DerivedClass : public BaseClass {
type name (...) override { ... }
};
override states that the derived-class function overrides a virtual function from the base class. The compiler reports an error if its signature does not match. The overriding function remains virtual, even without repeating the virtual keyword.
This is called dynamic binding or late binding.
Intermediate summary¶
Compile-time polymorphims: The compiler selects the unique best-matching overload based on the number and static types of the arguments.
Runtime polymorphism: For a virtual member function called through a pointer or reference, the implementation is selected at runtime based on the object’s actual type.
Pure virtual functions¶
struct Container {
virtual bool contains(double x) const = 0;
};
The = 0 marks contains as a pure virtual function.
This makes Container an abstract class: you can create pointers and references to it, but you cannot instantiate it.
A derived class must provide or inherit an implementation of every pure virtual function to become concrete and allow instantiation.
struct Interval : public Container {
bool contains(double x) const override {
return (low <= x) && (x <= high );
}
};
Interval overrides and implements the pure virtual function contains.
Since all inherited pure virtual functions are implemented, Interval is a concrete class and can be instantiated.
struct OpenInterval : public Interval {
bool contains(double x) const override {
return (low < x) && (x < high );
}
};
OpenInterval overrides the implementation of contains inherited from Interval.
contains remains virtual throughout the inheritance hierarchy, even when the virtual keyword is not repeated.
struct OpenInterval : public Interval {
bool contains(double x) const override final {
return (low < x) && (x < high );
}
};
The final keyword ensures that the virtual function contains cannot be overridden in any further derived class.
contains remains virtual throughout the inheritance hierarchy, even when the virtual keyword is not repeated.
struct OpenInterval final : public Interval {
bool contains(double x) const override {
return (low < x) && (x < high );
}
};
You can also mark an entire class as final to prevent other classes from inheriting from it.
Block C: Generic intervals with templates¶
Prompt: Modify the Interval class to be a template, replacing all double with the template type T. For
now, do not change any other code.
template <typename T>
struct Interval {
T high , low ;
Interval (T low , T high) : low (low), high (high) {}
bool contains (T x) const {
return (low <= x) && (x <= high);
}
bool contains (const Interval & other) const {
return (low <= other.low ) && (other.high <= high);
}
};
template <typename T>
struct Interval { ... };
This defines a class template with a type parameter T, specified at compile time:
Interval<double> A{0.0, 1.0};
Interval<int> B{0, 1};
Interval<double> and Interval<int> are distinct types, generated from the same template.
With great power comes great responsibility¶
#incude <complex>
Interval<std::complex<double>> C{std::complex<double>(5.0, 4.3),
std::complex<double>(-4.0, -7.7)};
std::cout << C.contains(0.0) << std::endl;
- Is there a shorter way to implement this?
- Is the default implementation correct?
The auto keyword¶
auto C = Interval{ std::complex<double>(5.0, 4.3),
std::complex<double>(-4.0, -7.7) };
auto D = Interval<std::complex<double>>{ {5.0, 4.3}, {-4.0, -7.7} };
auto lets the compiler deduce the variable’s type from its initializer at compile time.
Both variables have type Interval<std::complex<double>>.
For C, class template argument deduction also deduces the template argument of Interval; for D, it is specified explicitly.
Specialization¶
template <typename T>
struct Interval {
bool contains (T x) const {
return (low <= x) && (x <= high);
}
};
The operator <= is not defined for std::complex<double>, so instantiating contains for this type causes a compilation error.
template <typename T>
struct Interval { ... };
// Specialization for T = std::complex<double> outside(!) class
template <>
bool Interval<std::complex<double>>::contains(std::complex<double> x) const {
return (std::abs(low) <= std::abs(x)) && (std::abs(x) <= std::abs(high));
}
The specialization must match the original declaration, including the return type, parameter types, and const qualifier.
Define the specialization outside the class using the full qualified member name.
What did we learn in this lecture?¶
- Compile-time polymorphism: overloading of functions and operators
- Class inheritance
- Runtime polymorphism: virtual methods, override, and abstract classes
- Template meta-programming and specialization
- Automatic type deduction: auto