default and delete with example in C++

default and delete with example in C++ โ€” Rule of Five & Explicit Control

๐Ÿ”ท What are default and delete?

C++11 introduced these to allow explicit control over compiler-generated special member functions:

  • = default โ†’ Request the compiler to auto-generate the method.
  • = delete โ†’ Forbid the compiler from generating or using the method.

๐Ÿ”ถ Rule of Five โ€“ Where It Fits

In modern C++, if you define any one of the following, you should usually define all of them (the Rule of Five):

Special FunctionPurpose
DestructorCleanup on object destruction
Copy ConstructorCopy initialization
Copy Assignment OperatorCopy via =
Move ConstructorMove initialization (C++11+)
Move Assignment OperatorMove via = (C++11+)

You can use = default or = delete for any of them explicitly.

๐Ÿ”ธ Example: Rule of Five Using default and delete

class FileHandler {
public:
    FileHandler() = default;

    // Disable copy
    FileHandler(const FileHandler&) = delete;
    FileHandler& operator=(const FileHandler&) = delete;

    // Allow move
    FileHandler(FileHandler&&) = default;
    FileHandler& operator=(FileHandler&&) = default;

    ~FileHandler() = default;
};

โœ… This says:

  • Do not allow copying.
  • Allow move semantics.
  • Use default constructor and destructor.

๐Ÿ”ท = delete โ€” Also Useful for Preventing Misuse

โŒ Prevent Implicit Conversions

void print(int) = delete;

print(3.14);  // โŒ Compile-time error

โŒ Disable default constructor

class Singleton {
public:
    Singleton() = delete;
};