2

I am attempting to implement polymorphism with a templated derived class. See below:

//templated base class
template <class num> class A{
protected:
    num x;
    num y;

public:
    A( num x0 = 0, num y0 = 0) {
       x = x0;
       y = y0;
    }
    virtual void print_self() = 0;

};

//derived class
template < class num > class B: public A < num > {
   public:
      B( num x1 = 0, num y1 = 0):shape < num > ( x1 , y1 ) { }
      void print_self(){
          std::cout << "x is " << x << " and y is " << y << endl;
      }
};

The base class has pure virtual function print_self(). When trying to define the function in the derived class, I received the following error:

'x' was not declared in this scope

The same for y. So somehow the derived class doesn't have access to the variables x and y even though it is listed as protected.

Is there some other way to define print_self(), or is this simply not possible? If it is not possible, can you suggest another approach?

JoNeu
  • 23
  • 2

1 Answers1

2

Since you are using templated inheritance, the existence of x and y are dependent of the template argument. In other words the base class part of this pointer become a dependent name. You must use the this pointer explicitly or use using.

template<typename num>
struct B : A<num> {
    using A<num>::x;
    using A<num>::y;

    void print_self(){
        std::cout << "x is " << x << " and y is " << y << endl;
    }
};

Or even:

template<typename num>
struct B : A<num> {
    void print_self() {
        std::cout << "x is " << this->x << " and y is " << this->y << endl;
    }
};
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141