Using Constructors

C++ provides two ways to initialize an object by using a constructor. The first is to call the constructor explicitly:

Stock food = Stock("World Cabbage", 250, 1.25);

This sets the company member of the food object to the string "World Cabbage", the shares member to 250, and so on.

The second way is to call the constructor implicitly:

Stock garment("Furry Mason", 50, 2.5);

This more compact form is equivalent to the following explicit call:

Stock garment = Stock("Furry Mason", 50, 2.5));

C++ uses a class constructor whenever you create an object of that class, even when you use new for dynamic memory allocation. Here’s how to use the constructor with new:

Stock *pstock = new Stock("Electroshock Games", 18, 19.0);

This statement ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.