This post will discuss how to initialize an object in C++.

1. Using default constructor

We can use the default constructor to construct an object of a class, with all its fields initialized with default values. For example, the following code implicitly invokes the default constructor of the Point class.

Download  Run Code

Output:

(0, 0)

 
The following code explicitly invokes the default constructor of the class. Note that this is not an assignment, and the operator= is not called here.

Download  Run Code

Output:

(0, 0)

2. Using user-defined constructor

Another option is to provide the user-defined constructor and invoke it using the value initialization assignment syntax. This is the preferred option when one or more fields of the class need to be initialized with some custom value.

Download  Run Code

Output:

(1, 1)

 
The above code is equivalent to the following:

Download  Run Code

Output:

(1, 1)

3. Using member initialization

The following syntax calls the corresponding constructor if available. If no constructor is available, it simply performs member initialization.

Download  Run Code

Output:

(1, 1)

4. Using Pointers

To dynamically allocate memory for an object and initialize it with the supplied or the default values, use the new operator. You can do something like using pointers.

Download  Run Code

Output:

(1, 1)

 
In modern C++, switch to smart pointers from the C++ Standard Library to ensure that programs are free of memory leaks and are exception-safe. The following example shows how a std::make_unique pointer could be used to initialize an object.

Download  Run Code

Output:

(1, 1)

That’s all about initializing an object in C++.