Initialization With Constructors

Constructors are one of the crucial elements of any custom data types. Let's discuss how to use them in our Car example.

Basics of constructors

A constructor is a special member function that has the same name as the class name. You cannot invoke a constructor like other member functions. Instead, the compiler calls it when an object of its class is being initialized.

class Experiment {
public:
    Experiment() : a_(0), b_(10) { } // a default constructor
    Experiment(int a, int b) : a_(a), b_(b) { }

private:
    int a_;
    int b_;
};

The above example shows a class Experiment with two constructors. The first one is called a default constructor; it has no arguments.

The primary function of constructors is to initialize data members. In our case, these constructors use member initializer list: for example, a_(0), b_(10).

Get hands-on with 1200+ tech skills courses.