tailieunhanh - A Complete Guide to Programming in C++ part 30

A Complete Guide to Programming in C++ part 30. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | CONSTRUCTOR CALLS 269 Unlike other methods constructors cannot be called for existing objects. For this reason a constructor does not have a return type. Instead a suitable constructor is called once only when an object is created. Initialization When an object is defined initial values can follow the object name in parentheses. Syntax class object initializing_list During initialization the compiler looks for a constructor whose signature matches the initialization list. After allocating sufficient memory for the object the constructor is called. The values in the initialization list are passed as arguments to the constructor. Example account nomoney Poor Charles This statement calls the constructor with one parameter for the name. The other data members will default to standard values. If the compiler is unable to locate a constructor with a suitable signature it will not create the object but issue an error message. Example account somemoney Li Ed Error The class Account does not contain a constructor with two parameters. If a constructor with only one parameter is defined in the class the statement can be written with an equals sign . Example account nomoney Poor Charles This statement is equivalent to the definition in the example before last. Initialization with parentheses or the sign was introduced previously for fundamental types. For example int i 0 is equivalent to int i 0 . Default Constructor A constructor without parameters is referred to as a default constructor. The default constructor is only called if an object definition does not explicitly initialize the object. A default constructor will use standard values for all data members. If a class does not contain a constructor definition the compiler will create a minimal version of the default constructor as a public member. However this constructor will not perform initialization. By contrast if a class contains at least one constructor a default constructor must be defined explicitly if it is

TỪ KHÓA LIÊN QUAN