Constructor – creating the object

The constructor is a special function used to setup an object to a valid state.

  • The constructor must have the same name as the class.
  • The constructor does not have a return type.
  • There can be many constructors for the same class, the difference between them is the number and type of the parameters.

A constructor without any parameters is called the default constructor. If you don’t write a default constructor then one will be created for you automatically and setup the object with default values (which may not be what you want).

The constructor of the object is together with the destructor an important part of the RAII paradigm.

Multiple constructors

A class can have many constructors, and one common problem is that these will usually perform the same initialization of the member variables thereby creating redundant code. With the interest of keeping your code DRY, you should consider to extract the common elements into separate functions. The, in many cases, most natural solution to this would be to make the constructors call each other – but there is a pitfall here. Calling one constructor from another will only work in C++11, so if you have a compiler which supports C++11 you can do the following (called delegating constructors):

If you don’t have a C++11 compiler then the common solution is to extract a separate function which does the initialization:

 

Private Constructor

Normally is the constructor of a class a public member function. If a class has a private constructor, then it is not possible to create instances of the class anywhere else but in the class itself. This can be handy if you want all instances to be created in exactly the same way or in the same location using a static factory method.

 

 

Facebookgoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *