Why can't I add elements to my vector?
I have the following code in one class:
class A
{
std::vector<Parameter*> params;
std::vector<Parameter*> getParamVector() {return params;}
void addOneParam(Parameter* param)
{
params.push_back(param);
}
}
In another class, class B, I am trying to add items to the params vector by doing the following:
classA_Ptr->getParamVector().push_back(aParamPtr);
But the size of params is still 0 after the call above.
I need to add above method addOneParams(Parameter* param)
to add items to params vector . Why?
source to share
getParamVector()
returns a copy params
. So when you are push_back
at it, you add a temporary vector
one that is immediately removed. This does not affect the size in any way params
.
If you want to do this via getParamVector()
, you will need to return a link to params
:
std::vector<Parameter*>& getParamVector() {return params;}
^^^
source to share
You must return either by reference or by pointer as indicated.
std::vector<Parameter*>& getParamVector() { return params; }
or
std::vector<Parameter*>* getParamVector() { return ¶ms; }
But here's the real question: if you already have a method that can add one parameter, why would you need to call getParamVector (). push_back ().
Instead, you can just do classA_ptr-> addOneParam (p).
EDIT: For me, addOneParam () provides data hiding better than getting a reference / pointer to an inner vector.
If the data structure for storing parameters changes, the caller must also change.
With addOneParam (), the caller is isolated.
source to share