I declared vector<test*> test1; as a private, and I’d like to create getter and setter for this. I tried,
void setV(vector<test*> test1)
{
test1 = test1;
}
vector<test*> getV()
{
return test1;
}
It works, but it works very strange. Is there another way to do it?
Thanks
Look at the assignment statement in
setV:The private variable
test1is shadowed by the function parameter of the same name, and you’re assigning that parameter to itself.You should define
setVlike this:That way you’re really assigning the parameter to the private variable, and using a
constreference for the parameter avoids an unnecessary temporary copy.Also, you should define
getVasconst, and returning aconstreference:That way it can be called on a
constinstance of your class, and it avoids making an unnecessary copy for the return value.(You can also define another
getV, without theconsts, if you want the caller to be able to modify the vector of a non-const instance of your class.)