I'm trying to initialize a pointer array of same class objects. Here's the class:
class Correspondent{
private:
static Correspondent *correspondent[maxCorrespondents];
}
I tried in contsructor. but it got initialized every time.
Correspondent::Correspondent(string n,string c) {
name = n;
country = c;
for(int i=0;i<=maxCorrespondents;i++){
correspondent[i] = NULL;
}
}
In the one translation unit where this variable is defined:
Correspondent* Correspondent::correspondent[maxCorrespondents]{};
That's it. This aggregate initializes the array, which in turn default initializes each pointer. And since pointers are fundamental types, that will do zero initialization, setting them all to nullptr.
Objects with static storage duration are always zero-initialized. So correspondent array will be filled with zeros without writing any additional code. From [dcl.init].10
Every object of static storage duration is zero-initialized at program startup before any other initialization takes place.
Also it might be a good idea to use ::std::array wrapper and to introduce a type alias to avoid duplication in array declaration and definition:
class Correspondent
{
private: using Correspondents = ::std::array<Correspondent *, maxCorrespondents>;
private: static Correspondents correspondents;
};
Correspondent::Correspondents Correspondent::correspondents;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With