C + + Super-faq "Constructor"

Source: Internet
Author: User

    • What is a constructor function
Constructors build objects from dust. They turn a pile of arbitrary bits into a living object.
    • List x, List x () and list X (Bar ())
List x, declaring an object of type list named X, List X (), declaring a function named X, returning the list type; "LLVM hint" Empty parenthess interpreted as a function declartion "" List x (Bar ()), declares a function called X, contains a parameter of type Bar, returns the Type list. If you want to construct a list object named X through the temporary object Bar, it should be written as List X{bar ()},{} called uniform initialization (since c++11).
    • Whether other constructors of this type can be called in the constructor
C++11 increased constructor chainging makes this operation feasible. "Specific behavior also needs to be supplemented" c++11 before this operation is not feasible. Because the newly called constructor creates a temporary object in place, the statement is destroyed as soon as it finishes executing. The default constructor's call to the default constructor is a constructor that can be called without any arguments. Try to construct an array of objects using a vector instead of an array, because the former can specify which constructor to use, while the latter only uses the default constructor.
1 vector<fred> A (ten, Fred (5,7)); 2 Fred b[];
Exception: Using an array is more appropriate when you need the syntax "explicit initialization of arrays".
Fred a[Ten] ={Fred (5,7), Fred (5,7), Fred (5,7), Fred (5,7), Fred (5,7),//The ten Fred objects areFred (5,7), Fred (5,7), Fred (5,7), Fred (5,7), Fred (5,7)//initialized using Fred (5,7)};

    • Constructor initialization list Call order

Immediate base classes (left-to-right) and then member-objects (top to bottom).

Attention:

If member objects contains nesting, the nested objects must be declared before.

The Initialize list is initialized in the order of member objects declarations.

If the initialization of a member variable uses the value of another member variable, you must explicitly indicate the order of their declarations.

    • Accessing the this pointer in the constructor

Within the constructor body ({}), you can access the this pointer, because all data members are now ready.

However, the virtual function of the derived class override cannot be accessed in the constructor because this is not known to be a derived class object at this time.

    • Named Constructor Idiom

This is a technique that provides a more intuitive and secure way to construct classes.

"Named Constructor Idiom" can be used when a type contains many constructors and is not easily distinguishable by parameter types.

For example, point coordinates can use both Cartesian and polar coordinate systems, and their construction parameters are consistent. Their ordinary constructors can then be declared private and then accessed through named constructor for the user to construct.

Point P1 = point::rectangular (5.71.2);   // obviously rectangular Point P2 = point::p olar (5.71.2);         // obviously Polar

This technique can also be used if the user needs to ensure that the object must be created through new.

    • Does return-by-value mean extra overhead

Not necessarily.

Because, in some usages, the (business-level) compiler automatically optimizes, returning a pointer to a local object instead of a copy.

class Foo; Foo Method () {  return  Foo (...);} void   = Method (); // will optimize     = Method (); // Not necessarily optimized }

    • Static member declaration of a class

In addition to declaring a static member, the code must also contain the definition of the object, which would cause the link to "undefined external" incorrectly.

If a static const member is declared, it cannot be initialized by = when defined.

    • staticInitialization order fiasco

This is a subtle error that is extremely difficult to detect, and this error generally occurs before main () is called.

Eg: a static x x is defined in A.cpp, the static y y is defined in B.cpp, and the initialization of Y requires X, and the error occurs if X is not initialized before Y is initialized.

Generally used Construct on First use IdiomTo avoid these problems, a static object is wrapped around the function.
//File x.cpp#include"Fred.h"//Way OneFred x;//Mode twofred&x () {Staticfred* ans =NewFred (); return*ans;} //File y.cpp#include"Barney.h"Barney y;//File Barney.cpp#include"Barney.h"//Way OneBarney::barney () {// ...x.gobowling (); // ...}//Mode twoBarney::barney () {// ...x (). gobowling (); // ...}
The disadvantage of this usage is that the static object will never be destroyed.

Eg: an example of accessing an object before it is initialized by a predecessor declaration.

intf ();//Forward Declarationintg ();//Forward Declarationintx =f ();inty =g ();intf () {Std::cout<<"using ' Y ' (which is"<< y <<") \ n"; return 3*y +7;}intg () {Std::cout<<"initializing ' y ' \ n"; return 5;}
    • Named Parameter Idiom
The function parameter types in C + + are generally referred to as "positional parameters". The ADA language contains a parameter type called "named parameters". This type is useful for functions that have many parameters and use default values for most parameters. C + + usually has two methods to solve the problem: consolidating these parameters into a string, which is interpreted after passing to the function. All the Boolean parameters are integrated into a bit-map, which is passed to the function after interpretation. The workaround for Named Parameter idiom is that the function parameter is a function of a new type, which takes the form of a reference to this.
File f = OpenFile ("foo.txt")           . ReadOnly ()           . Createifnotexist ().           appendwhenwriting ()           . BlockSize(1024x768)           . Unbuffered ()           . exclusiveaccess (); class file {public:  file (constparams);   //  ...};
The OpenFile here is the newly created class, whose member functions allow you to set the property parameters of the file.

    • Keyword explicit

This keyword can be used for the decoration of constructors and conversion operators. The purpose is that the user must display the call when using these functions, avoiding implicit type conversion problems.

Reference: Https://isocpp.org/wiki/faq/ctors

C + + Super-faq "Constructor"

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.