Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inherited template classes & initialization lists

I have been converting some of my math classes to templates and to use initialization lists, and run into a problem when the inherited class needs to access base class data members on 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; };
};

Is it possible to use initialization lists on inherited classes?

like image 469
Shawn Buckley Avatar asked Feb 26 '23 06:02

Shawn Buckley


1 Answers

You need to invoke the base class constructor:

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

This would be no different if these were nontemplate classes: you can only initialize the base classes and member variables of the derived class in the derived class constructor.

like image 116
James McNellis Avatar answered Mar 06 '23 21:03

James McNellis