C ++ Inherited template classes and initialization lists

I convert some of my math classes to templates and use initialization lists and run into a problem when an inherited class needs access to the data elements of the base class during initialization.

Here is the code:

template <typename T>
struct xCoord2
{
    T x;
    T y;

    xCoord2(T _x, T _y) : x(_x), y(_y) {};
};

template <typename T>
struct xCoord3 : xCoord2<T>
{
    typedef xCoord2<T> B;

    T z;

    // All Error
    xCoord3(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {};
    xCoord3(T _x, T _y, T _z) : B::x(_x), B::y(_y), z(_z) {};
    xCoord3(T _x, T _y, T _z) : this->x(_x), this->y(_y), z(_z) {};

    // Works
    xCoord3(T _x, T _y, T _z) { B::x = 0; B::y = 0; z = 0; };
};

Can I use the initialization lists of inherited classes?

+3
source share
1 answer

You need to call the base class constructor:

xCoord3(T _x, T _y, T _z) : xCoord2(_x, _y), z(_z) { } 

It would be completely different if they were non-standard classes: you can initialize the base classes and member variables of the derived class in the constructor of the derived class.

+7
source

Source: https://habr.com/ru/post/1788278/


All Articles