What a Difference a default Makes
C++09 offers a neat solution to this problem by extending the semantics to the keyword default
. To force the compiler to generate a copy constructor for a class that wouldn't normally get one, declare the default constructor like this:
C(const C& rhs);
This way, the compiler will be forced to generate a default constructor for C
Notice how elegantly this new feature extends the meaning of default, a keyword that already exists in C and C++. To make default's new role distinct from its traditional use in switch statements, defaulted functions now adopt pure virtual functions' =specifier notation. The =default function specifier can be added to any of the special member functionsnot just the constructor.
|Author's Note: By mere coincidence, the word default is used in both default constructors and defaulted functions. Recall that a default constructor is simply a constructor that can be invoked with no arguments. To avoid confusion, I use the phrase "defaulted constructor" to refer to a constructor that is declared with the =default specifier.
The C++ standard states clearly when the compiler will implicitly declare a destructor for a class and when it won't. Here too, the rules don't always meet your design goals. With the =default specifier you can override them.
Suppose you're designing an interface for an asbtract pointing device:
virtual bool onRightClick(Point xy)=0;
virtual bool onDoubleClick(Point xy)=0;
You must declare a virtual destructor for this class because otherwise, the compiler will implicitly declare
a non-virtual destructor for it. Here's the catch: after you declare a destructor (virtual or not), you must define it as welleven if it's a dummy destructor:
In this example, you're forced to manually define a dummy destructor simply because it must
be virtual. As with the manual definition of a default constructor, a manual destructorhowever trivialis less efficient than an implicitly-defined one, and it imposes an unnecessary burden on the programmer. Ideally, you'd like to have the compiler generate a virtual destructor for you. Let's see how C++09 defaulted functions get it done:
virtual int onRightClick(Point xy)=0;
virtual int onDoubleClick(Point xy)=0;
The compiler now implicitly defines a virtual destructor for Pointing_device_interface
. The implicitly-defined destructor is as efficient as any implicitly-defined virtual destructor.
Remember, defaulted functions are only declared; you don't define them. The compiler will automatically define them for you.