Often, as with the Stock examples, you want to create several objects of the same class. You can create separate object variables, as the examples have done so far in this blog, but it might make more sense to create an array of objects.
Stock mystuff[4]; // creates an array of 4 stock objects
Recall that a program always calls the default class constructor when it creates class objects that aren't explicitly initialized. This declaration requires either that the class explicitly define no constructors at all, in which case the implicit do-nothing default constructor is used, or. as in this case, that an explicit default constructor be defined. Each element--mystuff[0], mystuff[1], and so on--is a Stock object and thus can be used with the Stock methods:
mystuff[0].update(); // apply update() to 1st element
mystuff[3].show(); // apply show() to 4th element
Stock tops = mystuff[2].topval(mystuff[1]);
// compare 3rd and 2nd elements
You can use a constructor to initialize the array elements, In that case, you have to call the constructor for each individual element:
const int STKS = 4;
Stock stocks[STKS] = {
Stock("NanoSmart", 12,5, 20),
Stock("Boffo Objects", 200, 2.0),
Stock("Monolithic Obelisks", 130, 3.25),
Stock("Fleep Enterprises", 60, 6.5)
};
Here the code uses the standard form for initializing an array: a comma-seperated list of values enclosed in braces. In this case, a call to the constructor method represents each value. If the class has more than one constructor, you can use different constructors for different elements:
const int STKS = 10;
Stock stocks[STKS] = {
Stock("NanoSmart", 12.5, 20),
Stock(),
Stock("Monolithic Obelisks", 130, 3.25),
};
This initializes stock[0] and stocks[2] using the Stock(const char * co, int n, double pr) constructor and stocks[1] using the Stock() constructor. Because this declaration only partially initializes the array, the remaining seven members are initialized using the default constructor.
The scheme for initializing an array of objects still initially use the default constructor to create the array elements. Then the constructors in the braces create temporary objects whose contents are copied to the array/vector. Thus a class must have a default constructor if you want to create arrays of class objects.
Abonneren op:
Reacties posten (Atom)
Geen opmerkingen:
Een reactie posten