Consider the following minimal example.
#include <vector>
class Data
{
std::vector<int>& v;
public:
Data(std::vector<int>& _v) : v(_v) {}
Data(const std::vector<int>& _v) : v(_v) {} // error!
};
int main()
{
std::vector<int> v;
const std::vector<int> c_v;
Data d(v);
Data const_d(c_v);
return 0;
}
This does not compile. The whole output from g++ -Wall
below.
const.cpp: In constructor ‘Data::Data(const std::vector<int>&)’:
const.cpp:8:41: error: invalid initialization of reference of type ‘std::vector<int>&’ from expression of type ‘const std::vector<int>’
The reason is clear to me: The const keyword is upset about my cast in line 8. The issue: I really sometimes need the Data class with std::vector
, but sometimes with const std::vector
. Like having two classes: One for reading into Data
, and one for reading from Data
. However, I do not like to write two Data classes with almost redundant functions. My questions:
- Can you give a nice solution to how I can achieve what I try to do in
main()
? C++11 solutions are pretty welcome, too :) - Is this the reason for
iterator
andconst_iterator
?