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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access