C++ - Classes & Objects
Overview
Estimated time: 45–60 minutes
Define classes with encapsulated state and behavior. Learn constructors, destructors, member initializer lists, and access control.
Learning Objectives
- Declare classes with public/private/protected members.
- Write constructors, destructors, and member initializer lists.
- Understand copy vs move basics and the Rule of Zero.
Prerequisites
Class with constructor and methods
#include <iostream>
class Counter {
  int value_ {0}; // private by default in class
public:
  Counter() = default;
  explicit Counter(int start) : value_{start} {}
  void inc(){ ++value_; }
  int value() const { return value_; }
};
int main(){
  Counter c{5};
  c.inc();
  std::cout << c.value() << "\n";
}
Expected Output: 6
Destructor and RAII
#include <iostream>
struct Tracer {
  ~Tracer(){ std::cout << "destroyed\n"; }
};
int main(){
  {
    Tracer t; // prints when leaving scope
  }
}
Expected Output: destroyed
Rule of Zero
Prefer standard containers and RAII-managed members so you don’t need to write copy/move/destructor explicitly. Let the compiler generate the right operations.
Special member functions: default, delete, copy/move
#include <utility>
struct Widget {
  int id{0};
  Widget() = default;                 // defaulted
  Widget(const Widget&) = delete;     // noncopyable
  Widget& operator=(const Widget&) = delete;
  Widget(Widget&&) noexcept = default; // movable
  Widget& operator=(Widget&&) noexcept = default;
};
Static members and helpers
struct Counter {
  static int instances; // declaration
  Counter(){ ++instances; }
};
int Counter::instances = 0; // definition
Common Pitfalls
- Exposing public data members widely—prefer private with accessors to maintain invariants.
- Forgetting to initialize members in the initializer list when necessary.
Checks for Understanding
- What does making a constructor explicitprevent?
- Why does RAII simplify resource management?
Show answers
- Prevents unintended implicit conversions.
- Resources are acquired in constructors and released in destructors automatically with scope.
Exercises
- Create a class Stopwatchthat starts in the constructor and prints elapsed time in the destructor.
- Refactor a class to make its invariant explicit via private members and public const accessors.