List of C + + member initialization

Source: Internet
Author: User

1. What is a member initialization list

#include <iostream>#include<string>using namespacestd;classweapon{Private:    stringname; Const stringtype; Const stringmodel; Public: Weapon (stringNamestringTypestringmodel)    : Name (name), type (type), model (model) {Name="Cloud"; }    stringGetProfile () {return "Name:"+ name +"\ntype:"+ Type +"\nmodel:"+model; }};intMainvoid) {Weapon Weapon ("Comet","Carbine","Rifle"); cout<< Weapon.getprofile () <<Endl; Cin.Get(); return 0;}

The red part of the code above is the member initialization list

Notice that the name of the constructor is "Cloud"; The value of the initialized list is overridden by the

2. Why a member initialization list is required

Both type and model are constants that can be initialized but cannot be assigned, and an error will be made if an assignment such as type = "XXX" is attempted in the function body of the constructor. Conceptually, before entering the function body of a constructor, the object has been created, so initialization must be done before the object is created, so C + + has invented the initialization list, which is considered to be initialization.

Please note: 1. This format can only be used for constructors;

2. You must use this method to initialize a non-static const data member (static const data is not part of the object so it cannot be initialized in the constructor);

3. Reference data members must be initialized in this format (this is because the reference is similar to the const data and can only be initialized at creation time)

List of C + + member initialization

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.