C/C++ Arena

Classes and objects in C++

Member variables and functions, public and private, constructors, initializer lists and const member functions.

A class bundles data with the functions that work on it. Keep the data private and expose public member functions, so the class can guarantee its invariants (rules that are always true, like "balance is never negative").

A constructor sets up a new object; use the member initializer list (: balance_(start)) to initialize fields. Mark member functions that don't change the object const, so they can be called on const objects.

Inside a member function, this points at the object it was called on.

Example

#include <iostream>

class Counter {
public:
    explicit Counter(int start) : count_(start) {}
    void increment() { ++count_; }
    int value() const { return count_; }

private:
    int count_;
};

int main() {
    Counter c(10);
    c.increment();
    c.increment();
    std::cout << c.value() << "\n";
    return 0;
}

Output:

12

Watch it run: An object and its member functions

Practice it