Modern C++ is really amazing with a lot of great features of programming. One of the features of Modern C++ is a Defaulted Function or in another term Defaulted Method of classes that is a function that contains =default;
in its prototype. Defaulted functions are a feature of C++11 and above. In this post, we explain what is a defaulted function or method in modern C++.
What is defaulted function or method in Modern C++?
A defaulted function (actually defaulted method, they are functions in classes) is a function that contains =default;
in its prototype. This construction indicates that the function’s default definition should be used. Defaulted functions are a C++11 specific feature.
If you have a method (including construction method) and you want to make it defaulted method, just add ‘=default;’ specifier to the end of this method declaration to declare that method as an explicitly defaulted method (or explicitly defaulted function).
Is there a simple example of a defaulted function or method in modern C++?
Here is an example to demonstrates defaulted function:
1 2 3 4 |
class Tmyclass { Tmyclass() = default; // OK }; |
This will allow the compiler generate the default implementations for explicitly defaulted methods which are more efficient than manually programmed method implementations.
Here is another example class.
1 2 3 4 5 |
class A { A() = default; // OK A& operator = (A & a) = default; // OK void f() = default; // ill-formed, only special member function may default }; |
What is defaulted function or method in Modern C++?
For example, if we have a parameterized constructor, we can use the ‘=default;’ specifier in order to create a default method. Because the compiler will not create a default constructor without this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> class Tmy_class { public: Tmy_class(int x) // parameterized constructor { std::cout << "a parameterized constructor"; } Tmy_class() = default; // defaulted constructor }; int main() { Tmy_class my_object1; // constructed with defaults Tmy_class my_object2(1); // constructed with parametrized constructor return 0; } |
For more information on defaulted functions, see Defaulted functions Proposal document.
Here are more details about the related topic of a trivial default constructor in C++.
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.