Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 13 of 45 · C++

Lesson 20: Copy Constructor, Assignment Operator, Rule of Three/Five

Duration: 12 min

Copy Constructor, Assignment Operator, Rule of Three/Five\n\nWhen a class manages a resource (e.g., dynamic memory), you must define how copying and moving work. The Rule of Three states that if you define any of destructor, copy constructor, or copy‑assignment operator, you should usually define all three. C++11 added move semantics, extending the rule to Five (add move constructor and move‑assignment operator).\n\n---\n\n## Example: Rule of Five implementation\ncpp\nclass Buffer {\n std::size_t size_;\n char* data_;\npublic:\n // Constructor\n explicit Buffer(std::size_t s) : size_(s), data_(new char[s]) {\n std::fill(data_, data_ + size_, 0);\n }\n // Destructor\n ~Buffer() { delete[] data_; }\n // Copy constructor\n Buffer(const Buffer& other) : size_(other.size_), data_(new char[other.size_]) {\n std::copy(other.data_, other.data_ + other.size_, data_);\n }\n // Copy‑assignment operator\n Buffer& operator=(const Buffer& other) {\n if (this != &other) {\n delete[] data_;\n size_ = other.size_;\n data_ = new char[size_];\n std::copy(other.data_, other.data_ + size_, data_);\n }\n return *this;\n }\n // Move constructor\n Buffer(Buffer&& other) noexcept : size_(other.size_), data_(other.data_) {\n other.size_ = 0;\n other.data_ = nullptr;\n }\n // Move‑assignment operator\n Buffer& operator=(Buffer&& other) noexcept {\n if (this != &other) {\n delete[] data_;\n size_ = other.size_;\n data_ = other.data_;\n other.size_ = 0;\n other.data_ = nullptr;\n }\n return *this;\n }\n // Simple accessor\n std::size_t size() const { return size_; }\n};\n\n\nBy handling copy and move explicitly, you avoid double‑deletes and enable efficient transfers.\n\n> Tip: If a class can be safely copied with the default behaviour, = default is preferable to writing boilerplate.\n\n---\n\n<Alert type="info">The Rule of Zero suggests preferring standard containers (std::vector, std::string) that already implement the rule of five for you.

Previous: Lesson 2: Setting Up Development EnvironmentNext: Lesson 21: Operator Overloading