class controls the default initialization process through a special constructor, which is the default constructor, and the default constructor does not require any arguments. The definition default constructor we can display also allows the compiler to generate a default constructor for us. The default constructor initializes the tired data member with the following rules:
- If an initial value exists in the class, it is used to initialize the member.
- Otherwise, the member is initialized by default.
Class Sales_data {public:std::string bookno;unsigned units_sold = 0;double revenue = 0.0;};
As shown above, because Sales_data provides an initial value for Units_sold and revenue, the composition default constructor uses these values to initialize the corresponding member, and Bookno is initialized to an empty string by default.
The composition default constructor is only available for very simple classes, and generally we need to provide a default constructor for a custom class because:
- The compiler generates a default constructor for us only if it discovers that the class does not contain any constructors. Once we have defined some other constructors, this class will not have a default constructor unless we define a default constructor. Because a class needs to control object initialization in some cases, the class may need to control initialization in all cases.
- The default constructor for a composition may perform incorrect operations, such as for composite types (arrays and pointers), and the result of default initialization is undefined.
- Some compilers cannot synthesize a default constructor for some classes, such as a class that contains a member of another class type, and the type of the member does not have a default constructor.
Default keyword:
Class Sales_data {public:sales_data () = default; Sales_data (const std::string &s) Bookno (s) {}sales_data (const std::string &s, unsigned n, double p): Bookno (s), UN Its_sold (n), revenu (p*n) {}sales_data (Std::istream &); std::string ISBN () const {return bookno;} sales_data& Combine (const sales_data&);d ouble avg_price () const;private:std::string bookno;unsigned units_ Sold = 0;double revenue = 0.0;};
In the C++11 standard, if we need the default behavior, we can ask the compiler to generate a default constructor later in the argument list. Default can appear either inside the class or as a definition outside of the class, both with the declaration. If =default is inside a class, the default constructor is inline, and if it is outside the class, the member function is not inline by default.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[C++11] Default constructor