Constructor (object-oriented Programming) - C++

C++

In C++, the name of the constructor is the name of the class. It does not return anything. It can have parameters, like any member functions (methods). Constructor functions should be declared in the public section.

The constructor has two parts. First is the initializer list which comes after the parameter list and before the opening curly bracket of the method's body. It starts with a colon and separated by commas. You are not always required to have initializer list, but it gives the opportunity to construct data members with parameters so you can save time (one construction instead of a construction and an assignment). Sometimes you must have initializer list for example if you have const or reference type data members, or members that cannot be default constructed (they don't have parameterless constructor). The order of the list should be the order of the declaration of the data members, because the execution order is that. The second part is the body which is a normal method body surrounded by curly brackets.

C++ allows more than one constructor. The other constructors cannot be called, but can have default values for the parameters. The constructor of a base class (or base classes) can also be called by a derived class. Constructor functions cannot be inherited and their addresses cannot be referred. When memory allocation is required, the operators new and delete 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 implemented by hand the compiler gives a default implementation which 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.

class Foobar { public: Foobar(double r = 1.0, double alpha = 0.0) // Constructor, parameters with default values. : x(r*cos(alpha)) // <- Initializer list { y = r*sin(alpha); // <- Normal assignment } // Other member functions private: double x; // Data members, they should be private double y; };

Example invocations:

Foobar a, b(3), c(5, M_PI/4);

You can write a private data member function at the top section before writing public specifier. If you no longer have access to a constructor then you can use the destructor.

Read more about this topic:  Constructor (object-oriented Programming)