0

I have created a variable in base class that is a vector of template but I'm not able to access this member from the derived class , can someone explain?

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

/*
 * 
 */
template <typename T>
class Apple{
protected:
public:
    vector<T> vec;
    virtual void foo(T node) =0;
};

template <typename T>
class Ball:public Apple<T>{
public:
    void foo(T node){
        cout<<"hahaha\n";
        vec.push_back(node);/* I GET COMPILATION ERROR HERE"vec was not declared in this scope"*/
    }
};

int main(int argc, char** argv) {
    Ball<int> b;
    b.foo(10);
    return 0;
}
Pavani siva dath
  • 455
  • 2
  • 5
  • 12
  • 2
    "I GET COMPILATION ERROR HERE" - is the error not shared because you don't want us to know what it is? – UKMonkey Feb 12 '18 at 13:07
  • it's not private use `this->vec` – Mihayl Feb 12 '18 at 13:09
  • 2
    Code posted compiles fine. I'm flagging as not reproducible. – UKMonkey Feb 12 '18 at 13:11
  • 1
    This [might](https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members) be helpful, but I don't think it applies since `vec` is a dependent name. – Arnav Borborah Feb 12 '18 at 13:12
  • @UKMonkey I can't compile this with either [GCC 7.2](https://wandbox.org/permlink/IXnG95It6yklM1Kk) or [Clang 5.0](https://wandbox.org/permlink/zhj611bNcZCi42Tp) (Copy/Pasted exactly as is). On what compiler is this working? – Arnav Borborah Feb 12 '18 at 13:16

2 Answers2

2

The member vec is of a template parameter dependent type so the compiler needs some help like:

this->vec.push_back(node);

or use qualified name:

Apple<T>::vec.push_back(node)

Thanks to @Avran Borborah - Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?

Here’s the rule: the compiler does not look in dependent base classes (like B<T>) when looking up nondependent names (like f).

This doesn’t mean that inheritance doesn’t work. ...

Mihayl
  • 3,821
  • 2
  • 13
  • 32
  • Why should we give scope resolution here ,Is that because I'm using template class?? – Pavani siva dath Feb 12 '18 at 13:19
  • Yes, look at the link @Avran Borborah posted - [Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?](https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members) – Mihayl Feb 12 '18 at 13:21
0

You have not created any private members in the base class. To resolve the error, you can replace the line which produces compilation error with : Apple::vec.push_back(node); or this->vec.push_back(node)

JDoe
  • 96
  • 2
  • 10