C++C++
IntermediateLesson 9 of 18

Classes, Constructors and Destructors – C++

Your own types with data and behavior – including const methods and operators.

A class bundles data (member variables) and functions (methods). private hides details, public is the interface. The constructor initializes the object – best via the member initializer list after the colon.

#include <iostream>
#include <string>
#include <utility>

class Konto {
public:
    Konto(std::string inhaber, double saldo = 0.0)
        : inhaber_(std::move(inhaber)), saldo_(saldo) {}

    void einzahlen(double betrag) { saldo_ += betrag; }
    double saldo() const { return saldo_; }                  // const: changes nothing
    const std::string& inhaber() const { return inhaber_; }

private:
    std::string inhaber_;
    double saldo_;
};

int main() {
    Konto k("Ada", 100);
    k.einzahlen(50.5);
    std::cout << k.inhaber() << ": " << k.saldo() << '\n';   // Ada: 150.5
}

struct is a class whose members are public by default – ideal for simple data bundles. You can overload operators; since C++20, = default generates the comparison automatically.

#include <iostream>

struct Punkt {
    double x = 0, y = 0;
    Punkt operator+(const Punkt& o) const { return {x + o.x, y + o.y}; }
    bool operator==(const Punkt&) const = default;    // C++20
};

std::ostream& operator<<(std::ostream& os, const Punkt& p) {
    return os << '(' << p.x << ", " << p.y << ')';
}

int main() {
    Punkt a{1, 2}, b{3, 4};
    std::cout << a + b << ' ' << std::boolalpha << (a == b) << '\n';   // (4, 6) false
}

The destructor (~Name) runs automatically when an object reaches its end – even with exceptions. RAII rests on exactly this:

#include <iostream>
#include <string>
#include <utility>

class Logger {
public:
    explicit Logger(std::string n) : name_(std::move(n)) { std::cout << "start " << name_ << '\n'; }
    ~Logger() { std::cout << "end " << name_ << '\n'; }
private:
    std::string name_;
};

int main() {
    Logger a("A");
    { Logger b("B"); }
    std::cout << "middle\n";
}   // output: start A, start B, end B, middle, end A
TipAlways mark methods that do not modify the object with const. Give single-parameter constructors explicit, so that no surprising implicit conversions arise.
WarningMembers are initialized in the order of their declaration – not in the order of the initializer list. If one member depends on another, the declaration order has to fit.