Home > Enterprise >  Using pointers in Class Templates with Subclasses
Using pointers in Class Templates with Subclasses

Time:12-19

I have a problem with using pointers with Class templates. I can't properly access vv from the B subclass if 'vv' stores pointers to vectors; if I simply store vectors it works. But what I'm trying to do requires me to store pointers. I honestly have no idea what I'm doing wrong so here is the code:

template<typename T>
class A{
    public:
        std::vector<std::vector<T>*> vv;
        void add(std::vector<T> new_vec)
        {
            vv.push_back(&new_vec);
        }

        virtual void print(){}
        virtual ~A(){}
};

template<typename T>
class B : public A<T>{
    public:
        void print() override{
            std::cout << this->vv[0]->at(0) << std::endl;
        }
};

int main(){
    int i = 10;
    std::vector<int> v;
    v.push_back(i);
    
    A <int>*a = new B<int>();
    a->add(v);
    a->print();
    return 0;
}

a->print() prints 0 instead of 10. Also I can't change what is inside main(). I would be very thankful for some help!

CodePudding user response:

Here:

    void add(std::vector<T> new_vec)
    {
        vv.push_back(&new_vec);
    }

You store a pointer to the local argument new_vec in vv. That local copy will only live till the method returns. Hence the pointers in the vector are useless. Dereferencing them later invokes undefined behavior. If you really want to store pointers you should pass a pointer (or reference) to add. Though, you should rather use smart pointers.

  • Related