Video Coming Soon...

Created by Zed A. Shaw Updated 2026-06-19 17:00:40

58: Constructors and Destructors

Now that we know about classes we can learn how the resources a class needs are initialized. Talk about RAII, how C++ implements it (wrong?), and how it fits with a destructor for resource cleaning.

The Code

I think this code is missing a destructor for the example. It shows the AnnoyingPerson that has a typical constructor that builds its data from the constructor's parameters.

View Source file ex58.cpp Only

#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>

class AnnoyingPerson {
  std::string name;
  int age;
  // NOTE: need a way to demonstrate destructors too

public:
  AnnoyingPerson(const std::string& name, int age)
    : name(name), age(age) { }

  int getAge() {
    return age;
  }

  const std::string& getName() {
    return name;
  }

  void setAge(int age) {
    this->age = age;
  }

  void setName(const std::string& name) {
    this->name = name;
  }
};

int main(int argc, char* argv[]) {
  // try doing the initialize like before to see the error
  AnnoyingPerson zed{"Zed", 51};

  fmt::println("I am {} and I am {} years old.",
      zed.getName(), zed.getAge());
}

The Breakdown

line of code
Description.

The Discussion

Blah blah.

The Jank of this->

Talk about why people use m_, why I use $ and why anything you choose is an equally jank workaround for this->.

Further Study

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.