Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Change the Rules of C++ with Defaulted Functions

C++ has rigid rules regarding the automatic generation of the four canonical member functions. Overriding these rules hasn't been possible thus far. However, the new C++09 defaulted functions give you more control over the compiler's generated canonical functions.


advertisement

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


rogrammers have little control over the implicit declarations of the four canonical member functions. The compiler will not generate a default constructor for a class that has a user-declared copy-constructor. This frustrating state of affairs is about to change. The deleted and defaulted functions proposal provides a convenient mechanism for just this type of per-class customization. The following sections will show you how to use defaulted functions.


In certain cases, you need to define a default constructor manually, because the compiler will not implicitly-declare it. Not only is manual constructor definition tedious, it's also not very efficient.


Use the new =default function specifier to make the compiler generate a member function that wouldn't be generated otherwise.



Presenting the Problem
Suppose you're designing a class that requires a user-defined copy constructor:

class C { public: C(const C& rhs); };

Later, when you try to create an object for this class, you get a compilation error:

C obj;//error: no default constructor exists for class C C * pc= new C; //same error

This kind of error can baffle even experienced programmers. Wasn't the compiler supposed to implicitly declare a default constructor for class C? No, it wasn't. When you declare a copy constructor in a class, the compiler doesn't implicitly-declare a default constructor in that class. What if you want the compiler to generate a default constructor for you anyway? In C++03, there's no way to override these language rules; you simply have to define the missing default constructor manually:

class C { public: C(const C& rhs); C() {} //manual definition of a default constructor }; C obj; //OK

Not only is this tedious, the user-defined default constructor is often less efficient than the compiler's implicitly-defined default constructor.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date