Let's say I have the following code which, in short, has:
- a
BaseClass
with a pointer to aPointerClass
- a
ChildClass
that inherits fromBaseClass
- a
HolderClass
that has anstd::vector
ofChildClass
s and anstd::vector
ofBaseClass*
s:
The entire code is as follows:
#include <stdlib.h>
#include <time.h>
#include <vector>
class PointerClass {
public:
int num;
double num2;
PointerClass() {
srand(time(NULL));
num = rand() % 100;
num2 = rand() % 100 / 2.0;
}
};
class BaseClass {
public:
PointerClass *pointerClass;
};
class ChildClass: public BaseClass {
public:
ChildClass() {
pointerClass = new PointerClass();
}
};
class HolderClass {
public:
std::vector<BaseClass*> basePointerVec;
std::vector<ChildClass> childVec;
HolderClass() {
}
void addParentClass() {
ChildClass childClass = ChildClass();
childVec.push_back(childClass);
basePointerVec.push_back(&childClass);
}
};
int main(int argc, const char * argv[]) {
HolderClass holderClass = HolderClass();
for (int count = 0; count < 20; count++) {
holderClass.addParentClass();
}
for (int count = 0; count < holderClass.basePointerVec.size(); count++) {
delete holderClass.basePointerVec[count]->pointerClass;
}
return 0;
}
My problem is, after adding a pointer to the ChildClass
into the std::vector<BaseClass*> basePointerVec
and the actual ChildClass
into the std::vector<ChildClass> childVec
in the addParentClass()
method in HolderClass
, the data in basePointerVec
andchildVec
are completely different.
Furthermore, when I try to free the PointerClass
es from the childVec
, everything works fine. But when I try to free them from the basePointerVec
instead, I get an error telling my I'm trying to free a pointer I have not allocated memory for.
And sure enough, when I use breakpoints to inspect everything, I find some funky behavior. It seems that every time I call ChildClass childClass = ChildClass();
in addParentClass()
, every pointer in basePointerVec
gets changed to point to the newly created ChildClass
's BaseClass
.
The point of me doing this in my actual program is to take advantage of polymorphism and have multiple classes inherit from BaseClass
.
So my question is, why is every pointer in the vector being changed to point to the newly created class and how can I fix it?
P.S. sorry for the length of this question, it's as short as I could possibly make it