The construction function of C + + class and the example _c language

Source: Internet
Author: User
Tags class definition constructor

Constructors for C + + classes

Default constructor

If you define a class and do not define a constructor for it. The compiler provides the default constructor for this class. If you provide a constructor, the compiler will not provide you with a default constructor. The default constructor provided by the compiler did nothing. The member variables of the class are subject to the default initialization rules.

Initialization rules for default constructors provided by the compiler:

The built-in or composite type member variables for class objects in stacks and heaps will be dirty data;

The built-in or composite type member variable of the class object in the global variable area is initialized to 0;

The class object member invokes the default constructor to initialize;

#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

Constructors with default arguments

As with normal functions, you can specify a default value for the parameters of a constructor.

If you define a default constructor for a class, you define a constructor that has a default value for all parameters. (Technically, this is overloaded) a compilation error is generated when the class object is constructed with the default constructor. Because the compiler does not know which overloaded function to select.

Initialization list of constructors

In addition to assigning a value to a class member with an explicit assignment expression in the function body of the constructor (which, strictly conceptually, is not initialized), the recommended practice is to use the initialization list. The initialization list begins with a colon, followed by a comma-delimited list of data members, followed by an initializer in parentheses. The initialization list of constructors can only be specified in the implementation and cannot be specified in the definition body. The implementation of a class's member functions (constructors are no exception) can be either in the definition body of the class (inline function) or in the implementation of the class.

Initialization order for members

Each member can be specified only once in the initialization list. and the order in which members appear in the initialization list does not represent the actual initialization order of the members. The initialization order of members is based on the order in which they appear in the class definition. So the initialization of members is best not to depend on each other, and if you are sure that they are dependent on each other, you have to know the order in which they appear in the class definition.

Two stages of constructing a constructor function

(1) The initialization phase (based on the default variable initialization rules and initialization list), (2) The function body execution phase of the constructor (in which case the assignment statement in the constructor body executes).

Why is it recommended to use an initialization list?

1. In many classes, initialization and assignment are strictly inefficient: data members may have been initialized directly, and initialized and assigned values.
2. More important than the efficiency mentioned in 1th is that certain 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 and cannot be assigned a value. Initialization must be completed before execution of the constructor body. Assigning values to them in the body of a function can cause a compilation error.

A member variable of a class type should also be particularly aware that if you do not initialize it in the initialization list, the compiler will attempt to initialize it by invoking its default constructor at the initialization stage. If it does not have a default constructor, this will result in a run-time error. Another scenario is that you assign only the members of a class object in the constructor body. The initialization phase will call the default constructor of the class object member, and the calculation phase will call the constructor body's specified constructor. This means that the object member of the class calls two constructors, and the second one overwrites the first.

Constructors and implicit type conversions, explicit

C + + supports type auto conversion. You can define how objects from other classes are implicitly converted to our class types, or we can implicitly convert our class-type objects to other types. The constructor has an implied rule that a constructor called with a single argument class defines an implicit conversion from that parameter type to the class type. Sometimes this is not what you want, and it can cause errors. For example, you define 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 box box= second Initializes a box object. The compiler converts 2 implicitly to a box object, which is equivalent to invoking the constructor box (2).

If you pass in an int argument in a function call that requires a box type parameter, a temporary box object is constructed and the function is passed as a parameter. After the function is over, the box object disappears, what's the use? This is almost certainly a mistake. For this we can:

1. Implicit conversions with keyword explicit to prevent constructor definitions

You can block implicit conversions by adding the explicit keyword before the declaration of the class constructor (note that you cannot add it in the definition).

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

If you define a box object again: Box box = 2 or if the Int type object is passed as an argument to a function as a box object, a compilation error will be thrown.

2. Use a constructor that you display each time you convert. This prevents an implicit conversion.
Call the constructor of the class using Func (Box (2)) in a function call that requires a Box object argument to create a temporary object to prevent automatic implicit conversions.

Recommendation: Constructors that can be invoked with a single argument should be defined as explicit unless there is a clear reason to allow implicit conversions.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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.