C ++ Note 1: Class Constructor

Source: Internet
Author: User

Default constructor

If you define a class without defining the constructor for it. The compiler will provide the default constructor for this class. If you provide constructors, the compiler will no longer provide you with a default constructor. The default constructor provided by the compiler does nothing. Class member variables follow the default initialization rules.

The default constructor initialization rules provided by the compiler:

Built-in or composite member variables of class objects on stacks and stacks will be dirty data;

The built-in or composite member variables of class objects in the global variables area are initialized to 0;

Class Object members will call the default constructor for initialization;

#include <iostream>using namespace std;class Box{public:int length;int width;};Box box1;int main(){Box box2;Box *pbox3 = new Box;cout<<"box1.length == "<<box1.length<<" box1.width == "<<box1.width<<endl;cout<<"box2.length == "<<box2.length<<" box2.width == "<<box2.width<<endl;cout<<"box3.length == "<<pbox3->length<<" box3.width == "<<pbox3->width<<endl;return 0;}

The result of the above Code is:

Box1.length = 0 box1.width = 0
Box2.length = 2686792 box2.width = 1987092020
Box3.length = 3811912 box3.width = 3801284

 

Constructor with default real parameters

Just like a common function, you can specify the default value for the constructor parameters.

If you define a default constructor for a class and a constructor with default values for all parameters. (Technically, this is a heavy load) A compilation error occurs when class objects are constructed using the default constructor. The compiler does not know which overload function to choose.

 

List of constructor Initialization

In addition to assigning values to class members using a clear value assignment expression in the constructor body (strictly speaking, this is not initialization), we recommend that you use the initialization list. The initialization list starts with a colon, followed by a list of data members separated by commas. Each data member is followed by an initialization formula in parentheses. The initialization list of the constructor can only be specified in the implementation but not in the definition body. The implementation of the class member functions (constructor is no exception) can be either in the class definition body (Inline Function) or in the class implementation.

 

Initialization order of members

Each member can only be specified once in the initialization list. In addition, the order in which Members appear in the initialization list does not represent the actual initialization order of members. The initialization sequence of members is based on the order they appear in the class definition. Therefore, it is recommended that the initialization of Members do not depend on each other. If you are sure that they are dependent on each other, you must know the order in which they appear in the class definition.


Two phases of constructor Construction

(1) initialization phase (based on the default variable initialization rules and the initialization list); (2) the execution stage of the function body in the constructor. (The Value assignment statement in the constructor is executed ).


Why is the initialization list recommended?

1. In many classes, initialization and assignment are strictly inefficient: data members may have been directly initialized, and initialization and assignment are required.

2. More important than the efficiency mentioned at the first point is that some types of data members must be initialized.

Some types of Members must be initialized in the initialization list, such as the const object and the reference type object. They can only be initialized, but cannot be assigned a value. Initialization must be completed before the constructor is executed. Assigning values to them in the function body will cause compilation errors.

Special attention should also be paid to the member variables of the class type. If you do not initialize it in the initialization list, the compiler will try to call its default constructor to initialize it during the initialization phase. If it does not have the default constructor, this will cause a runtime error. In another case, you only assign values to the members of the class object in the constructor body. In the initialization phase, the default constructor of the Class Object member is called, and in the computing phase, the specified constructor In the constructor is called. This indicates that the class Object Member calls the constructor twice, and the second will overwrite the first constructor.


Constructor and implicit type conversion, explicit it

C ++ supports automatic type conversion. You can define how to implicitly convert the objects of other classes to our class type, or implicitly convert our class type objects to other types. Constructor has an implicit rule: A constructor called by a single real-name class can be used to define an implicit conversion from this parameter type to this type. Sometimes this is not what you want and will cause errors. For example, you have defined the following class.

class Box{public:Box(int x=1,int y=1);int length;int width;};Box::Box(int x,int y):length(x),width(y){}

If you use Box = 2 to initialize a box object. The compiler implicitly converts 2 to a Box object, which is equivalent to calling the constructor Box (2 ).

If you input an int real parameter in the function call that requires the box type parameter, a temporary box object will be constructed and then the function will be passed as the parameter. After the function is completed, the box object disappears. What is the purpose? This is almost certainly an error. We can:

1. Use the keyword explicit to block the implicit conversion defined by the constructor.

Adding the explicit keyword before the class constructor declaration can prevent implicit conversion.

class Box{public:explicit Box(int x=1,int y=1);int length;int width;};

If you define a box object as follows: Box box = 2 or pass an int type object as a box object to a function, a compilation error will occur.
2. the constructor is displayed for each conversion. This prevents implicit conversion.

Func (box (2) is used to call the class constructor in function calls that require real parameters of the box object to create a temporary object to Prevent Automatic implicit conversion.


Suggestion: unless there is a clear reason for implicit conversion, constructors that can be called with a single parameter should be defined as explicit.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.