C++ PROGRAMMING ยท 16 MIN STUDY

Classes and objects

A class defines a type that combines state with operations that keep that state meaningful.

Learning objectives

  • Define a class with private data and public member functions.
  • Construct an object and call its operations.

Prerequisites: variables, functions, and basic type declarations. Constructors and class invariants are developed further in later lessons.

Model a useful thing

Complete C++17 program
#include <iostream>

class Counter {
public:
    explicit Counter(int start) : value{start} {}

    void increment() {
        ++value;
    }

    int current() const {
        return value;
    }

private:
    int value;
};

int main() {
    Counter visits{0};
    visits.increment();
    std::cout << visits.current() << '\n';
}
Expected output 1

The class defines a type; visits is an object of that type. The constructor initializes the private member value. The call to increment() changes the object's state, and current() reads it. Code outside the class cannot assign value directly, but it can use the public operations. The trailing const on current() promises that this member function will not modify the object through that call. This complete program can be compiled as written.

Why encapsulation helps

Encapsulation lets a type protect its invariants: rules that must remain true. If a bank balance must not become invalid, expose operations that validate deposits and withdrawals rather than letting any caller change the raw number.

Common mistakes

  • End a class definition with a semicolon.
  • Do not make every member public by default; decide what callers truly need.
  • Keep a class focused on one coherent responsibility.

Practice

  1. What is the difference between a class definition and an object?
  2. Why is value private in the Counter example?
  3. What does the trailing const on current() communicate?
Show reasoned answers
  1. The class defines a type; an object is an instance of that type.
  2. It prevents callers from changing internal state except through the class's public operations.
  3. The member function promises not to modify the observable state of the object through that call.

References