1

The following snippet is in a header file:

// Represents NxN scalar values (aka square matrix).  
template<std::size_t N>
class dummy
{ 
    public:
    float& operator[](const std::size_t ind) { return scalars[ind]; }

    private:
    float scalars[N*N];
};

using dummy2 = dummy<2>;

And this is how I would use it:

// 2x2=4 floats
dummy2 d;

std::cout << d[0] << std::endl; // prints 0
std::cout << d[1] << std::endl; // prints 0
std::cout << d[2] << std::endl; // prints -1.42253e+19
std::cout << d[3] << std::endl; // prints 4.59163e-41

My question is why do not the last two print calls result in a zero value?

pepe
  • 814
  • 8
  • 12

2 Answers2

4

You didn't provide a constructor for your class, so the compiler generates a default one, which default-initialises all members of the class. And default-initialising a built-in type means it's not initialised at all, so any use of its value is undefined. In other words, scalars is not initialised to anything.

You can fix it like this:

template<std::size_t N>
class dummy
{ 
    public:
    float& operator[](const std::size_t ind) { return scalars[ind]; }

    dummy() : scalars()
    {}

    private:
    float scalars[N*N];
};

using dummy2 = dummy<2>;

This makes scalars value-initialised instead of default-initialised, and value-initialising a float sets it to 0.f, so everything will work.

Live example

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

scalars is not initialized explicitly. The first two zeros are actually the result of undefined behaviour, so you should set the array to zero in the constructor.

anderas
  • 5,744
  • 30
  • 49