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
x开发者_开发知识库Coord3(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?
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.
精彩评论