0

I have a class X with an std::array member variable:

class X
{
   public:
     //some code here

   private:
     std::size_t var1_;
     std::array<std::uint8_t, 100> var2_; //this is the class member variable
}

I want to ensure that var1_ and var2_ are always initialized even if I do not explicitly initialize them in the constructor. If I do something like this:

  class X
    {
       public:
         //some code here
    
       private:
         std::size_t var1_{0};
         std::array<std::uint8_t, 100> var2_{}; //this is the class member variable
    }

it will initialize var1_ to zero. Does the use of {} for var2_ guarantee that all the uint8_t array elements will be initialized to zero? Also if the use of {} ensures that all the array elements are initialized to zero, is there a way to initialize them to some value other than 0, at the line where var2_ is defined? (i.e., without doing it explicitly in the constructor). I am using C++11. Thanks

astrophobia
  • 839
  • 6
  • 13
  • 3
    *"Does the use of {} for var2_ guarantee that all the uint8_t array elements will be initialized to zero"* Yes, see https://en.cppreference.com/w/cpp/language/aggregate_initialization *"is there a way to initialize them to some value other than 0"* No. – HolyBlackCat Aug 31 '21 at 18:46
  • *" is there a way to initialize them to some value other than 0"* It should be straightforward to write a function like `template std::array MakeArray(T val)` that manufactures an array initialized to copies of a given value. Then you can write `std::array var2_{MakeArray(42)};` – Igor Tandetnik Aug 31 '21 at 18:50

0 Answers0