bhylu.com

Advertisements

C++ Classes and Objects

Keep a parcel load nonnegative and below capacity through a narrow public interface.

How it works

A class bundles state with operations that preserve its rules. Private members stop callers from assigning arbitrary values directly. The public interface should express useful domain actions rather than expose a setter for every field. This Load type starts empty, has a fixed positive capacity and reports whether a requested addition fits. Its invariant is that used stays between zero and capacity. Encapsulation is useful because every permitted operation can be reviewed against that one rule.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror classes.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · classes.cpp

#include <iostream>

class Load {
    int used_{0};
    static constexpr int capacity_{10};
public:
    bool add(int count) {
        if (count < 0 || count > capacity_ - used_) { return false; }
        used_ += count; return true;
    }
    int used() const { return used_; }
};

int main() {
    Load load;
    std::cout << "Added: " << load.add(4) << '\n';
    std::cout << "Too many: " << load.add(9) << '\n';
    std::cout << "Used: " << load.used() << '\n';
}

Expected result

Added: 1
Too many: 0
Used: 4

The subtraction check relies on the maintained invariant and rejects the update before mutation. used() is const because observation should not alter this load. The failed request leaves state unchanged. A struct could implement the same interface with explicit private access; class simply makes private the default. Avoid making every field public merely to simplify one test.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.