Lets assume we have a base class Base
class Base{
virtual double GetNumber();
}
and multiple child classes (let's call them 'A', 'B' and 'C') that look like
class A : public Base{
double GetNumber(){return 1;};
}
Now I do have another class which should receive a child class through a function. It looks like this:
class Caller(){
Base* b;
void SetB(Base* b){this->b = b;};
}
I do only pass the pointer to prevent object slicing. However from where i want to call the function it looks like this:
std::vector<Caller> cVec; //multiple Caller object in here
for (std::vector<Caller>::iterator it = cVec.begin(); it != cVec.end(); ++it){
A child;
//Some manipulation of child
cVec.SetB(&child);
}
The pointer solves the problem of object slicing, however I do not want all Caller objects pointing to the same child. I could solve it by creating another vector with multiple instances of the child classes but I wonder if there is a better way to do this?
Edit 1: The child object should only be created in the for loop and managed by the Caller object.