Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
Yobot (talk | contribs)
m WP:CHECKWIKI error fixes using AWB (10820)
Line 241:
The constructor has two parts. First is the [[initializer list]] which follows the [[parameter (computer science)|parameter list]] and before the method body. It starts with a colon and entries are comma-separated. The initializer list is not required, but offers the opportunity to provide values for data members and avoid separate assignment statements. The initializer list is required if you have ''const'' or reference type data members, or members that do not have parameterless constructor logic. Assignments occur according to the order in which data members are declared (even if the order in the initializer list is different).<ref>http://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order Constructor</ref> The second part is the body, which is a normal method body enclosed in curly brackets.
 
C++ allows more than one constructor. The other constructors canmust have different parameters. Additionally constructors which contain parameters which are given default values, formust adhere to the restriction that not all parameters are given a default value. This is a situation which only matters if there is a default constructor. The constructor of a [[base class]] (or base classes) can also be called by a derived class. Constructor functions are not inherited and their addresses cannot be referenced. When memory allocation is required, the ''new'' and ''delete'' operators are called implicitly.
 
A copy constructor has a parameter of the same type passed as ''const'' reference, for example ''Vector(const Vector& rhs)''. If it is not provided explicitly, the compiler uses the copy constructor for each member variable or simply copies values in case of primitive types. The default implementation is not efficient if the class has dynamically allocated members (or handles to other resources), because it can lead to double calls to ''delete'' (or double release of resources) upon destruction.