Creating objects

You can create objects on the stack or in the free store. Using the previous example, this is as follows:

    cartesian_vector vec { 10, 10 }; 
cartesian_vector *pvec = new cartesian_vector { 5, 5 };
// use pvec
delete pvec

This is direct initialization of the object and assumes that the data members of cartesian_vector are public. The vec object is created on the stack and initialized with an initializer list. In the second line, an object is created in the free store and initialized with an initializer list. The object on the free store must be freed at some point and this is carried out by deleting the pointer. The new operator will allocate enough memory in the free store for the data members of the class and for any of the infrastructure the class needs.

A new feature of C++11 is to allow direct initialization to provide default values in the class:

    class point 
{
public:
int x = 0;
int y = 0;
};

This means that if you create an instance of point without any other initialization values, it will be initialized so that x and y are both zero. If the data member is a built-in array, then you can provide direct initialization with an initialization list in the class:

    class car 
{
public:
double tire_pressures[4] { 25.0, 25.0, 25.0, 25.0 };
};

The C++ Standard Library containers can be initialized with an initialize list, so, in this class for tire_pressures, instead of declaring the type to be double[4] we could use vector<double> or array<double,4>, and initialize it in the same way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset