1

I am writing a general Vector class and I want a Vector3 class to inherit from Vector. Vector's data can be of any length, Vector3's data is of length 3. So I want to make a different constructor for Vector3 which accesses the Vector's data and length. For this question I simplified the code.

#include <iostream>


template <typename T>
class A {
protected:
    T value;

public:
    A()
    : value(0)
    {};

    A(T value)
    : value(value)
    {};

    ~A ()
    {};

    T get_value()
    {
        return value;
    }
};

template <typename T>
class B : public A<T> {
public:
    B()
    : A<T>(3)
    {};

    T test()
    {
        return value; // error: 'value' was not declared in this scope
    }
};

As I said I want to access 'value' in the child class 'B', however I get the error notification

error: 'value' was not declared in this scope

However according to the c++ website (http://www.cplusplus.com/doc/tutorial/polymorphism/) I should be able to access 'value'.

Why is this, and more important, how do I solve this?

suitendaal
  • 149
  • 9
  • You are using the term [attributes](https://en.cppreference.com/w/cpp/language/attributes) incorrectly in a C++ context. – Jesper Juhl Jan 25 '20 at 16:15
  • I highly recommend reading [dependent_name](https://en.cppreference.com/w/cpp/language/dependent_name). It may be difficult to read at first but is really useful when you're not just looking for a quick fix but actually understand how names are looked up esp. when dealing with templates. – Empty Space Jan 25 '20 at 16:18

1 Answers1

0

This is a sticky bit of C++. Since you're inheriting from A<T>, not A, the member names are not visible by default. They're called non-dependent names because they don't depend on the template parameter. I generally import members I want to use explicitly:

template <typename T>
class B : public A<T> {
   using A<T>::value;
public:
    B()
    : A<T>(3)
    {};

    T test()
    {
        return value; // error: 'value' was not declared in this scope
    }
};
gct
  • 14,100
  • 15
  • 68
  • 107
  • Okay, but should I do this every time I inherit from A or B? Inheritance should make life earier right? Not more difficult – suitendaal Jan 25 '20 at 17:12
  • Yes you'll have to do it everytime you define a class inheriting from A, but not when you use them so it's not really a burden. You can also access the members through the `this` pointer. – gct Jan 25 '20 at 17:27