Reputation: 545
I have a simple question. I have a class say A with a private member that is a stl container, for example a vector of ints. Is there a way to use its methods (e.g. size, resize, etc...) ? Does the classic "get function" suffice ?
Class A
{
private:
std::vector<int> v;
public:
std::vector<int> get_v() {return v;};
};
If yes, isn't a "get function" meant to only get the member and not to modify the member ?
Thank you very much
Upvotes: 0
Views: 230
Reputation: 311048
Your get method returns a copy of the data member. So such a method does not allow to modify the original vector,
If you want to provide an access to elements of the vector you can either overload operator[] or write a get method with a parameter.
For example
Class A
{
private:
std::vector<int> v;
public:
int operator []( std::vector<int>::size_type n ) const { return v[n]; }
int & operator []( std::vector<int>::size_type n ) { return v[n]; }
};
or you can write get methods that do the same
Class A
{
private:
std::vector<int> v;
public:
int get( std::vector<int>::size_type n ) const { return v[n]; }
int & get( std::vector<int>::size_type n ) { return v[n]; }
};
As for the idea to use a copy of the vector or a reference to it that to get its size then it is not a good idea. It is better to provide a method that returns the size of the vector. In this case the user interface will not depend on the type of the container.
Upvotes: 0
Reputation: 234745
The normal thing to do here is to return a constant reference to the data member:
const std::vector<int>& get_v() const
{
return v;
}
Note that I've also made the function constant. This tells you that the function will not modify any data members in the class.
Currently, you are taking a deep copy of the vector, which is expensive in terms of performance and also detaches you from the original data.
If you want to call methods like resize
(that change the vector) then you can also supply a non-constant version of the function (overloading on const
) is allowed in C++):
std::vector<int>& get_v()
{
return v;
}
The compiler will call the const
version if you have a const
pointer (or reference) to an instance of A
. Else if will call the non-const
version.
Upvotes: 3
Reputation: 110698
That getter will return a copy of the internal vector. Any modifications you make will only affect the copy. That might be okay if you also provide a setter so that the modified copy can be passed back, so you could do something like this:
A a;
std::vector<int> v = a.get_v();
v.push_back(5);
a.set_v(v);
Alternatively, you can make the getter return a reference to the internal vector (so its return type would be std::vector<int>&
, then you can modify it from outside.
Upvotes: 0