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 Function | Purpose |
|---|---|
| Destructor | Cleanup on object destruction |
| Copy Constructor | Copy initialization |
| Copy Assignment Operator | Copy via = |
| Move Constructor | Move initialization (C++11+) |
| Move Assignment Operator | Move 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;
};