I created a composite pattern with Component, Leaf and Composite Classes, where only the Composite Class has both a member variable vector and add method:
void add(Component *a);
vector < Component * > children;
In a separate class B, I created a method getComponent() to return a Composite member variable
Class B: public A
{
Composite m_Comp;
public:
Composite * getComponent()
{
Leaf myLeaf1;
Leaf myLeaf2;
Composite myComp1;
myComp1.add(&Leaf1)
myComp1.add(&Leaf2)
Leaf myLeaf3;
m_Comp.add(&myComp1);
m_Comp.add(&myLeaf3);
m_Comp.inspect()
return &m_Comp;
}
};
when I inspect mypCompCheck it looks right, but when I retrieve it (?) from main:
A* myA;
AuxClass myAuxObject;
myA=myAuxObject.returnReferenceToClassBObject();
Composite * mypComp=myA->getComponent();
mypComp->inspect()
mypComp is not the same object. Is it wrong the way I think to return it?
Here my alternative way, after reading Is returning references of member variables bad practice?, but still not working...
Class B: public A
{
public:
Composite m_Comp;
setComponent()
{
Leaf myLeaf1;
Leaf myLeaf2;
Composite myComp1;
myComp1.add(&Leaf1)
myComp1.add(&Leaf2)
Leaf myLeaf3;
m_Comp.add(&myComp1);
m_Comp.add(&myLeaf3);
m_Comp.inspect();
}
};
and in main
A* myA;
AuxClass myAuxObject;
myA=myAuxObject.returnReferenceToClassBObject();
myA=myAuxObject.m_Comp.inspect();
when I inspect the object into the get method, it correctly shows all its components, including nested ones. When I do it in main, I see the myComp1 inside m_Comp as a Component instead than as a Composite.
Because of that, and because similar design with std objects (instead of Composite ones) work, I wondered if there was possibly something wrong in how I work with composite, more than in how I'm returning the member variable... I mean, I'm adding by references those components through the add method, and they are then limited in scope?
Thus, I replaced all the local variables with member ones, and it works...
Class A
{
Leaf m_Leaf1;
Leaf m_Leaf2;
Composite myComp1;
Leaf myLeaf3;
public:
Composite m_Comp;
setComponent();
{
m_Comp1.add(&m_Leaf1)
m_Comp1.add(&m_Leaf2)
m_Comp.add(&m_Comp1);
m_Comp.add(&m_Leaf3);
m_Comp.inspect();
}
};
and in main
A myA;
myA.m_Comp.inspect();
I got some fruitful learning, thanks to your hints and related searches.