-3

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.

Django
  • 5
  • 4
  • 6
    It's not clear what you are trying to do. Your code is flawed since A is a local variable that will disappear once the for loop exists. – Anon Mail Jan 13 '17 at 21:28
  • `class Caller(){};` I never saw a function/class declared this way – Raindrop7 Jan 13 '17 at 21:33
  • 1
    This looks like a genuine question with some reasonable effort to understand the problem on your part, but the way you've put it, it's really unclear what it is. If you don't want some pointers to point to the same object, then just don't have them point to the same object? – Christian Hackl Jan 13 '17 at 21:35
  • It looks like you just need to do dynamic allocation: `cVec.SetB(new A);` to get a different `A` each time through the loop. – Barmar Jan 13 '17 at 21:55
  • There's a fundamental question to have to answer for your design: is `Caller` supposed to take ownership over the child passed into `SetB` or does it only refer to a child whose lifetime is managed elsewhere in the program? A lot of other details will follow from that. – TheUndeadFish Jan 14 '17 at 00:00

1 Answers1

0

Thanks for the comments! The solution was as simple as just doing:

std::vector<Caller> cVec; //multiple Caller object in here
for (std::vector<Caller>::iterator it = cVec.begin(); it != cVec.end(); ++it){
cVec.SetB(new A(p1, p2...));
}

In the Caller objects I then handle the deletion later on.

Django
  • 5
  • 4
  • You're setting yourself up for tragedy and pain. Use [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) to express and enforce single ownership and manage the lifetime of the object. – Captain Obvlious Jan 14 '17 at 14:50