Codectionary / Developer documentation / C++

C++ Classes & RAII

Classes group data and functions. Constructors establish valid state. C++ uses RAII: an object owns a resource for its lifetime and releases it in its destructor.

Syntax

class Timer {
public:
  Timer();
  ~Timer();
};

Examples

Encapsulating state

A small, runnable example of this syntax.

#include <iostream>

class Counter {
public:
  void increment() { ++value_; }
  int value() const { return value_; }
private:
  int value_ = 0;
};

int main() {
  Counter counter;
  counter.increment();
  std::cout << counter.value() << "\n";
}

Best practices

  • Initialize members in constructors and prefer automatic objects over manually managed resources.
  • Keep examples small while learning, then combine the idea with a real project.

At a glance

Purpose
Systems and general-purpose software
File extension
.cpp ยท .hpp
Runs in
Compiled native applications
Usually used with
Compiler and standard library

Specifications & further reading

Related C++ documentation