child class not able to access parent member

1.5k views Asked by At

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;
}
2

There are 2 answers

0
JDoe On

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)

2
Mihayl On

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. ...