Reputation: 155
If I have vector
or another object as a class property, then how should I implement a getter for that property? Should it return the member itself or reference of it? Example below:
#include "B.h"
#include <vector>
class A {
vector<int> numbers;
B obj1;
public:
vector<int> get_numbers() const;
// or
vector<int> & get_numbers() const;
B get_obj() const;
// or
B & get_obj() const;
};
Note: Also I am not sure about the const
.
Upvotes: 2
Views: 919
Reputation: 238381
vector<int> & get_numbers() const;
Definitely not this. You'll find it difficult to return a reference to non-const referring to a member from a const qualified member function.
vector<int> get_numbers() const;
This is an option. But there are considerations:
To avoid unnecessary copying, you can return a reference to const instead:
const vector<int> & get_numbers() const;
To avoid even more unnecessary copying by allowing move construction from the getter, you can use a set of overloads:
const vector<int> & get_numbers() const & ;
vector<int> && get_numbers() &&;
To allow modification, you can use a non-const qualified member function returning a reference:
vector<int> & get_numbers() & ;
Another approach is to not use a getter at all. If the user of the class needs access to the member, then perhaps it should be public.
You could instead provide other forms of limited access. An Idiomatic C++ way would be to have begin
and end
member functions that return iterators. This would allow changing the content of the vector without allowing resizing it.
Upvotes: 3