C + + constructors

Source: Internet
Author: User

A constructor is a special member function that executes a constructor whenever a new object of the class type is created. The constructor works by guaranteeing that the data members of each object have the appropriate initial values. The constructor has the same name as the class name and cannot specify a return type. Like any other function, they can have no formal parameters, You can also define multiple parameters. Use an example to illustrate this.

<span style= "FONT-SIZE:14PX;" >class sales_item{public  :     sales_item (): Units_sold (0), Revenue (0.0) {}  private:      std::string ISBN;  ISBN      unsigned units_sold;//volume of books sold      double revenue;  Income};</span>
This constructor initializes the Units_sold and revenue members using the constructor initialization list. The ISBN member is implicitly initialized to an empty string by the default constructor of string.

Whenever a Sales_item object is created, the default constructor is called to initialize the data member, and the result of the preceding code runs:


The constructor initialization list begins with a colon, followed by a comma-delimited list of data members followed by an initialization expression that is placed in parentheses. Constructors can be defined inside or outside a class. Constructor initialization is specified only in the definition of the constructor, not in the declaration.



1. Constructors can be overloaded

There is no limit to the constructors that can be declared for a class, as long as the formal parameter list for each constructor is unique. Add an accept string argument constructor for the above code


<pre name= "code" class= "CPP" ><span style= "FONT-SIZE:14PX;" > #include <iostream> #include <string>using namespace Std;class sales_item{public  :     Sales_ Item (): Units_sold (0), Revenue (0.0) {}     Sales_item (const string& S);     void Display (); Show data member       private:      string ISBN;  ISBN      Unsigned units_sold;//sales of book volume      double Revenue;//revenue}; void Sales_item:: Display () {cout<< "ISBN:" & lt;<isbn<<endl; cout<< "Units_sold:" <<units_sold<<endl; cout<< "Revenue:" <<REVENUE<<ENDL;} Sales_item::sales_item (const string& S) {  isbn=s;  units_sold=0;  revenue=0;} int main () {  sales_item A;  Sales_item B ("haha");  cout<< "default constructor:" <<endl;  A.display ();  cout<< "constructor with string parameter:" <<endl;  B.display ();    return 0;} </span>

2. Arguments determine which constructor to use

3. Constructor Automatic execution

Whenever you create an object of that type, the compiler runs a constructor.

4. Constructors cannot be declared as const

Conceptually, it can be considered that the constructor is divided into two phases: (1) The initialization phase (2) the normal calculation phase.

The calculation phase consists of all the statements in the body of the constructor.

Data members of a class type are always initialized in the initialization phase, regardless of whether the member displays initialization in the constructor initialization list. Initialization occurs before the start of the calculation phase.

<span style= "FONT-SIZE:14PX;" >sales_item::sales_item (const string& S) {  isbn=s;  units_sold=0;  revenue=0;} </span>

The ISBN member is initialized before executing the above constructor. This constructor implicitly initializes the ISBN with the default string constructor. When the function body of the constructor is executed, the ISBN member already has values. The value is overridden by an assignment in the body of the constructor function.
in our programming, it's best to develop a good habit of initializing members with initialization lists. Effective C + + clause 4 says that constructors are best to use member initial values instead of using assignment operations within the constructor body. There is no difference between initializing lists and using assignment operations for data members that are built-in types, but for classes that have class-type Narimoto in data members such as the Sales_item class, it is more expensive to call a string class overload assignment operator without using the initialization list.
Note: Some members must be initialized in the constructor initialization list. For such members, assigning values to them in the constructor body does not work. A member of a class type without a default constructor, and a member of a const or reference type , regardless of type, must be initialized in the constructor initialization list. Because you can initialize objects of const objects or reference types, you cannot assign values to them. The only chance to initialize a const or reference type data member is in the constructor initialization list.
get into the habit of using initialization lists without worrying about these problems.

the order in which member initialization is initiatedconstructors, the order in which members are initialized is the order in which members are defined. The first member is initialized first, and so on.consider the following class:
<span style= "FONT-SIZE:14PX;" >class X {  int i;  Int J; Public:   X (int val): J (Val), I (j) {}};</span>

The above code will error because I was first initialized, and the effect of this initialization list is to initialize I with a J value that has not been initialized!

default real participation Constructors
Class sales_item{public   :     sales_item (const std::string &book = ""): IBSN (book), Units_sold (0), Revenue (0.0 {}      Sales_item (Std::istream &is)};

For any of the following definitions, the constructor that accepts the default argument as a string parameter is executed: Sales_item empty; Sales_item primer_3rd_ed ("0-201-82470-1");
You can reduce code duplication by using the default argument.
default constructorThe default constructor is used whenever an object is defined without an initializer. A constructor that provides default arguments for all parameters also defines a default constructor.
1. The default constructor for compositingeven if a class defines only one constructor, the compiler will no longer generate a default constructor, and the compiler will automatically generate a default constructor only if a class does not have a constructor defined. However, if the class does not have a constructor defined, the compiler does not necessarily provide a default constructor.There are four scenarios in which the compiler will be the composition default constructor1: Member class with default/constructor pair image2: Base class object with default/constructor3: Class containing virtual function 4: Classes that inherit virtual base classes
The composition's default constructor initializes the member with the same rules as the variable initialization. Members that have class types are initialized by running their respective default constructors. Members of built-in and composite types, such as pointers and arrays, are initialized only for objects defined in the global scope.  Members of built-in or composite types are not initialized when an object is defined at a local scope. If a class contains members of a built-in or composite type, the class should not rely on the composition's default constructor, and it should define its own constructors to initialize those members.
class should typically define a default constructor

Implicit type conversions     
<span style= "FONT-SIZE:14PX;" >class sales_item{public   :     sales_item (const std::string &book = ""): IBSN (book), Units_sold (0), Reven UE (0.0) {}      Sales_item (Std::istream &is)};</span>

Each of these constructors defines an implicit conversion, so a string or a IStream can be used where a Sales_item type object is expected;
string null_book = "9-999-99999-9";ITEM.SAME_ISBN (null_book);
This program uses a string type object as an argument to pass the SAME_ISBN function to Sales_item. The function expects a Sales_item object as an argument. The compiler uses a string that accepts a Sales_item constructor from null _book generates a new Sales_item object. The newly generated (temporary) Sales_item is passed to SAME_ISBN.
But implicit conversions are often not what we want, and can lead to errors that make us less able to image. You can prevent implicit conversions by declaring constructors as explicit .
<span style= "FONT-SIZE:14PX;" >class sales_item{public   :     explicit  sales_item (const std::string &book = ""): IBSN (book), Units_ Sold (0), Revenue (0.0) {}     explicit   Sales_item (Std::istream &is)};</span>

now, none of the two constructors can be used to create an object implicitly. The first two uses cannot be compiled:ITEM.SAME_ISBN (Null_book);//Error:string constructor is explicitITEM.SAME_ISBN (CIN); Error:istream constructor is explicit
Note: Normally, a single parameter constructor should be explicit, setting the constructor to explicit avoids errors, and when the conversion is useful, the user can construct the object in a display.

C + + constructors

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.