Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize static pointer array of objects of same class with nullptr?

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;
    }
}
like image 738
Gautam Chowdhury Avatar asked Jul 31 '26 23:07

Gautam Chowdhury


2 Answers

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.

like image 77
StoryTeller - Unslander Monica Avatar answered Aug 03 '26 14:08

StoryTeller - Unslander Monica


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;
like image 21
user7860670 Avatar answered Aug 03 '26 14:08

user7860670



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!