1

I am working with template classes for the first time, and trying to figure out why the compiler doesn't seem to like when I use inheritence.

Here is the code:

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

    xPoint2() { x = 0; y = 0; };
};

template <typename T>
struct xVector2 : xPoint2<T>
{
    xVector2() { x = 0; y = 0; };
};

The compiler output:

vector2.hh: In constructor ‘xVector2<T>::xVector2()’:
vector2.hh:11: error: ‘x’ was not declared in this scope
vector2.hh:11: error: ‘y’ was not declared in this scope

Is it not possible to use templates in this way?

Thanks

Shawn Buckley
  • 506
  • 6
  • 16
  • 1
    Consider using initializers rather than assignments in class constructors. – aschepler Jan 26 '11 at 21:38
  • In this particular case, you could also call the base class ctor, because it does the same. – Christoph Jan 26 '11 at 21:42
  • @Christoph: More accurately, you always call a base class ctor, whether you write such a call or not. So in this code the assignments in `xVector2()` are redundant - they've already been set to zero by the base constructor. – aschepler Jan 26 '11 at 21:45

2 Answers2

8

You need to help the compiler out by using this->x and this->y.

http://www.parashift.com/c++-faq/templates.html#faq-35.19

aschepler
  • 70,891
  • 9
  • 107
  • 161
4

You must explicitly refer to parent:

template <typename T>
struct xVector2 : xPoint2<T>
{
    typedef xPoint2<T> B;
    xVector2() { B::x = 0; B::y = 0; };
};
Foo Bah
  • 25,660
  • 5
  • 55
  • 79