Search⌘ K

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 ...