So let's say I have a few class objects, and this class owns a pointer to a Base component. I use pointers to take advantage of polymorphism. For simplicity, let's say that a Holder contains these class objects along with pointers to Derived, which inherits Base. Holder then instantiates each Object with the appropriate Derived.
My goal is to recycle these Derived components, that way I can just create Objects by using the same two instances of the Derived pointers.
class Holder{
public:
Holder(){
derivedOne = new Derived(paramX);
derivedTwo = new Derived(paramY);
Object objectX(derivedOne);
//so here I am recycling derivedTwo. My problem is that both objectY and ObjectZ
//are using the same components of derivedTwo, not separate ones.
Object objectY(derivedTwo);
Object objectZ(derivedTwo);
}
//...
private:
//the various derived components I want to use
Derived *derivedOne;
Derived *derivedTwo;
//here are the Objects
Object objectOne;
Object objectTwo;
};
//and here is the Object
class Object{
public:
Object(Base *d){
component = d;
}
private:
Base *component;
};
Anyways, my problem is that objectY and objectZ, which are instantiated with the same derivedTwo pointer, are using the same variables of DerivedTwo, not their own.
1 2 3
objectY.component->x = 10;
std::cout << objectZ.component->x; //prints out 10, but I want it to be 0 since
//I want objectZ to have its own component, not share it with objectY.
How would I get each Object to have access to their own elements of a certain Derived object, while having those two intial Derived pointers be the only Derived pointers that are created?
Those constraints are conflicting. If you only create one child for two parents, those two parents will share some state. If they can't share state then you need to create a child for each parent.
If possible, you can try moving out from the child the state that you don't want to be shared between the parents.
Then you set the component with the method in the Object class , that means you get another behavior but the location in memory for Component* m_component is the same . It is an alternative , but if you really want to recycle a block you should create an allocator .
that means you get another behavior but the location in memory for Component* m_component is the same
But that does not solve OP problem:
my problem is that objectY and objectZ, which are instantiated with the same derivedTwo pointer, are using the same variables of DerivedTwo, not their own.
If you inject new strategy throug one class, other will see object change too.
As it was pointed before and OP agreed with it, it cannot be adequately solved in current state and some changes to program architecture would be needed which will eliminate this problem as side effect.