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.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading