Basic C++ value class

by: Ethan McCue

A class in C++ is the same thing as a struct, just the class keyword makes the fields private by default instead of public by default with struct.

Here is a complete example of a simple "money" class

#pragma once

#include <cstdint>
#include <functional>
#include <ostream>
#include <optional>

namespace shopping {
    class Money final {
    private:
        constexpr explicit Money(std::uint32_t cents) noexcept: cents(cents) {};
        const std::uint32_t cents;

    public:
        constexpr static Money fromCents(std::uint32_t cents) noexcept {
            return Money(cents);
        };

        constexpr bool operator==(const Money& other) const noexcept {
            return this->cents == other.cents;
        };

        [[nodiscard]] constexpr std::uint32_t getCents() const noexcept {
            return this->cents;
        };

        friend std::ostream& operator<<(std::ostream &os, const Money &money) {
            os << "Money{cents=" << money.cents << "}";
            return os;
        };

        constexpr Money operator+(const Money& other) const noexcept {
            return Money::fromCents(this->getCents() + other.getCents());
        };

        constexpr std::optional<Money> operator-(const Money& other) const noexcept {
            if (other.getCents() > this->getCents()) {
                return std::nullopt;
            }
            else {
                return Money::fromCents(this->getCents() - other.getCents());
            }
        };
    };
}

namespace std {
    template <> struct hash<shopping::Money> {
        size_t operator()(const shopping::Money& money) const noexcept {
            return hash<uint32_t>{}(money.getCents());
        }
    };
}

This is the same as this rust

#[derive(Debug, Eq, PartialEq, Hash)]
struct Money(cents: u32);

Now maybe stop learning c++.


<- Index