warning: base class should be explictily initialized in the copy constructor

10,831

You're not initializing the base class in the copy constructor. Try this:

Matrix(const Matrix & that) : Elements<Elements<T, N>, M>(that) {
    /* ... */
}

The initializer list of the derived class' copy constructor should contain an explicit call to the base class' copy constructor, just like with all other constructors, otherwise, the base class will be default-initialized.

Edit: It can be handy to have a private

typedef Elements<Elements<T, N>, M> basetype;

in your class definition somewhere.

Share:
10,831
Tyler Jandreau
Author by

Tyler Jandreau

Updated on July 25, 2022

Comments

  • Tyler Jandreau
    Tyler Jandreau almost 2 years

    I'm writing a matrix class for CUDA processing.

    I've written a vector class (henceforth known as Elements) and used that for the matrix base.

    Here is the template definition:

    template <typename T, std::size_t M, std::size_t N>
    class Matrix : public Elements< Elements< T, N >, M > {
    
    }
    

    It should be noted that nothing is dynamically allocated in the Elements class, nor in the Matrix class.

    I'm getting a warning: base class ‘struct Elements<Elements<double, 2ul>, 2ul>’ should be explicitly initialized in the copy constructor warning in the copy constructor. Here is the copy constructor:

        DEVICE HOST
        Matrix(const Matrix & that) {
            for (std::size_t ind = 0; ind < M; ind++) {
                for (std::size_t jnd = 0; jnd < N; jnd++) {
                    (*this)[ind][jnd] = that[ind][jnd];
                }
            }
        }
    

    What am I doing wrong?

  • arne
    arne over 10 years
    @dyp: Thanks for spotting that - updated the answer accordingly.
  • Kindread
    Kindread over 10 years
    It would be more flexible to use the template arguments when invoking Element's constructor, or this might only compile when using a Matrix templated with a double type.
  • Tyler Jandreau
    Tyler Jandreau over 10 years
    That's exactly what I was looking for. I'm editing your answer to use typename T instead of double, explicitly. Otherwise, good show.