Welcome to this comprehensive lesson on C++11 Defaulted and Deleted Functions! In this tutorial, we'll be diving deep into understanding these powerful features, and learn how to leverage them in your own projects.
By the end of this lesson, you'll be able to:
Before C++11, when writing a class, you had to explicitly write all the special member functions, such as constructors, copy constructors, destructors, assignment operators, etc. This was not only tedious but also prone to errors.
Defaulted functions (= default) and deleted functions (= delete) were introduced in C++11 to simplify this process. They allow you to:
Defaulted functions are member functions that have their default implementations provided by the compiler. This means you can write a function header only, and the compiler will generate the default implementation for you.
To declare a defaulted function, use the = default keyword after the function declaration.
struct MyStruct {
MyStruct() = default; // Default constructor
MyStruct(const MyStruct&) = default; // Copy constructor
MyStruct& operator=(const MyStruct&) = default; // Copy assignment operator
};š Note: Defaulted functions are generated even if you provide a user-defined implementation. This can lead to confusion, so it's essential to understand when a defaulted function is being used.
Deleted functions are member functions that are explicitly marked as not being generated by the compiler. This is useful when you want to prohibit the use of a particular member function.
To declare a deleted function, use the = delete keyword after the function declaration.
struct MyStruct {
MyStruct(const MyStruct&) = delete; // Copy constructor is deleted
MyStruct& operator=(const MyStruct&) = delete; // Copy assignment operator is deleted
};š Note: Deleted functions cannot be called, and attempting to do so will result in a compile-time error.
Defaulted and deleted functions are powerful tools for writing cleaner, more efficient code. Here are some real-world use cases:
Copy and Move Operations
Constructors and Assignment Operators for Standard Library Types
std::vector have default constructors, copy constructors, and assignment operators.Initialization and Assignment of Base Classes
What is the purpose of a defaulted function in C++11?
How can you indicate that a special member function should not be generated in C++11?