After this lesson, you will be able to: Write C++ classes with constructors, destructors, member functions, and the Rule of Three/Five/Zero.
Classes are how C++ models real things. The Rule of Three/Five/Zero is what separates engineers who write C++ from engineers who write 'C with weird syntax.'
Every special member function (the Rule of Five) shown explicitly.
#include <iostream>#include <string>class User {private:std::string name_;int age_;public:// ConstructorUser(std::string name, int age) : name_(std::move(name)), age_(age) {}// Destructor (called on scope exit / delete)~User() { /* close files, free resources, etc. */ }// Copy constructor + copy assignment (Rule of Three)User(const User& other) = default;User& operator=(const User& other) = default;// Move constructor + move assignment (Rule of Five)User(User&& other) noexcept = default;User& operator=(User&& other) noexcept = default;// Member functions (const = doesn't modify *this)const std::string& name() const { return name_; }int age() const { return age_; }void birthday() { ++age_; }};int main() {User alex("Alex", 30);alex.birthday();std::cout << alex.name() << " is now " << alex.age() << "\n";}
In C++, `class` and `struct` are nearly identical, both can have member functions, constructors, inheritance. The only difference: `struct` members default to PUBLIC, `class` members default to PRIVATE. Convention: use `struct` for plain data (POD); use `class` when you have invariants to protect.
Rule of Three (C++98): if you define a destructor, copy constructor, or copy assignment, define ALL THREE. (They're related; missing one = bugs.) Rule of Five (C++11): same but also includes move constructor + move assignment. Rule of Zero (modern best practice): don't define ANY of them. Use member types that manage themselves (std::vector, std::string, std::unique_ptr) and the compiler synthesizes correct copy/move/destructor for you.
Pick the correct one.
Defining a destructor but no copy/move (double-free bugs). Java-style 'every method virtual' (zero-overhead violation). Using raw `new`/`delete` (use smart pointers). Forgetting `noexcept` on move constructors (containers fall back to copy = slower).
Sign in and purchase access to unlock this lesson.