|
Initialization of Aggregates
Explicit initialization of classes and arrays.
Just as you can explicitly initialize an array of characters using a literal string
char string [] = "Literal String";
|
you can initialize other aggregate data structures--classes and arrays. An object of a given class can be explicitly initialized if and only if all its non-static data members are public and there is no base class, no virtual functions and no user-defined constructor. All public data members must be explicitly initializable as well (a little recursion here). For instance, if you have
class Initializable
{
public:
// no constructor
int _val;
char const * _string;
Foo * _pFoo;
};
|
you can define an instance of such class and initialize all its members at once
Foo foo;
Initializable init = { 1, "Literal String", &foo };
|
Since Initializable is initializable, you can use it as a data member of another initializable class.
class BigInitializable
{
public:
Initializable _init;
double _pi;
};
BigInitializable big = { { 1, "Literal String", &foo }, 3.14 };
|
As you see, you can nest initializations.
You can also explicitly initialize an array of objects. They may be of a simple or aggregate type. They may even be arrays of arrays of objects. Here are a few examples.
char string [] = { 'A', 'B', 'C', '\0' };
|
is equivalent to its shorthand
Here's another example
Initializable init [2] = {
{ 1, "Literal String", &foo1 },
{ 2, "Another String", &foo2 } };
|
We used this method in the initialization of our array of FuncitionEntry objects.
If objects in the array have single-argument constructors, you can specify these arguments in the initializer list. For instance,
CelestialBody solarSystem [] = { 0.33, 4.87, 5.98, 0.64, 1900, 569, 87, 103, 0.66 };
|
where masses of planets are given in units of 1024kg.
Next.
|