peterboston
peterboston

Reputation: 927

Why can't I add items into 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 try to add items into the params vector by doing this:

classA_Ptr->getParamVector().push_back(aParamPtr);

But the params vector's size still 0, after above call.

I have to add above addOneParams(Parameter* param) method to add items into the params vector. Why?

Upvotes: 3

Views: 86

Answers (2)

KalyanS
KalyanS

Reputation: 527

You should return either by reference or pointer as pointed out.

std::vector<Parameter*>& getParamVector() { return params; }

or

std::vector<Parameter*>* getParamVector() { return &params; }

But, here is the real question: if you already have a method that can add one parameter, why do you need to call getParamVector().push_back().

Instead, you could just do classA_ptr->addOneParam(p).

EDIT: To me addOneParam() enforces data hiding better than getting a reference/pointer to the internal vector.

If the data structure to store the parameters changes, the caller will need to be modified as well.

With addOneParam(), the caller is insulated.

Upvotes: 3

Barry
Barry

Reputation: 302748

getParamVector() returns a copy of params. So when you push_back onto it, you're adding to a temporary vector that gets deleted right away. That in no way affects params's size.

If you want to be able to do this via getParamVector(), you'll have to return a reference to params instead:

std::vector<Parameter*>& getParamVector() {return params;}
                      ^^^

Upvotes: 14

Related Questions