![]() |
VOOZH | about |
What is a Defaulted Function?
Explicitly defaulted function declaration is a new form of function declaration that is introduced into the C++11 standard which allows you to append the '=default;' specifier to the end of a function declaration to declare that function as an explicitly defaulted function. This makes the compiler generate the default implementations for explicitly defaulted functions, which are more efficient than manually programmed function implementations.
For example, whenever we declare a parameterized constructor, the compiler won't create a default constructor. In such a case, we can use the default specifier in order to create a default one. The following code demonstrates how:
Output:
This is a parameterized constructor
In the above case, we didn't have to specify the body of the constructor A() because, by appending the specifier '=default', the compiler will create a default implementation of this function.
What are constrains with making functions defaulted?
A defaulted function needs to be a special member function (default constructor, copy constructor, destructor etc), or has no default arguments. For example, the following code explains that non-special member functions can't be defaulted:
What are the advantages of '=default' when we could simply leave an empty body of the function using '{}'?
Even though the two may behave the same, there are still benefits of using default over leaving an empty body of the constructor. The following points explain how:
Prior to C++ 11, the operator delete had only one purpose, to deallocate a memory that has been allocated dynamically.
The C++ 11 standard introduced another use of this operator, which is: To disable the usage of a member function. This is done by appending the =delete; specifier to the end of that function declaration.
Any member function whose usage has been disabled by using the '=delete' specifier is known as an explicitly deleted function.
Although not limited to them, but this is usually done to implicit functions. The following examples exhibit some of the tasks where this feature comes handy:
Disabling copy constructors
Disabling undesirable argument conversion
It is very important to note that A deleted function is implicitly inline. A deleted definition of a function must be the first declaration of the function. In other words, the following way is the correct way of declaring a function as deleted:
class C
{
public:
C(C& a) = delete;
};
But the following way of trying to declare a function deleted will produce an error:
What are the advantages of explicitly deleting functions?