Search code examples
c++operator-overloadingtemplate-classes

What is wrong with this simple C++ template class?


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?


Solution

  • 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