My first question here…
I want to use an abstract class A from which i derive a class B (and classes B2, B3, …). I understood that in order to handle them uniformly, I have to use pointers to the base class, so here variables of type A*.
In the example below, I want to fill aa which is of type vector<A*> in function f. Since I can only use references and the variables lose their scope at the end of f, I cannot access the members of the entries of aa in main anymore.
What could be a solution to this problem?
#include <vector>
#include <iostream>
class A {
public:
virtual int getVar(int, int) = 0;
};
class B : public A {
public:
B(std::vector<std::vector<int> > var) : var_(var) {};
int getVar(int i, int j) { return var_[i][j]; }
private:
std::vector<std::vector<int> > var_;
};
void f(std::vector<A*>& aa) {
std::vector<std::vector<int> > var(1, std::vector<int>(1));
var[0][0] = 42;
B b(var);
aa.push_back(&b);
}
int main() {
std::vector<A*> aa;
f(aa);
std::cout << aa[0]->getVar(0, 0) << std::endl;
return 0;
}
It is pushing the address of the local variable. That is the cause of the problem, because the local variable gets destroyed on returning from the functon, but
aastill contains the pointer to the non-existing object. Such a pointer is called dangling pointer using which invokes undefined behavior – which is one of the most dangerous and irritating aspect of C++.Use
new:Now it should work.
Important : Don’t forget to make
~A()virtual:It is necessary otherwise you wouldn’t be able to delete objects of derived type (in a well-defined way), using the pointers of base type.