Passing const reference

Hi everyone,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class S{
 public:
  string getData(){return data;}
  S(const string&);
 private:
  const string data;
};

S::S(const string& d)
{
 data=d;
}


int main()
{ 
 S myStr("Hello World");
cout<<"Data is "<<myStr.getData()<<endl;

}

This gives me error saying const.cpp: In constructor S::S(const std::string&):
const.cpp:30: error: passing const std::string as this argument of std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] discards qualifiers

I guess it is expecting const std::basic_string<_CharT, _Traits, _Alloc>& and I am giving it const std::string. I thought the compiler handles whether it should pass a variable by reference or value depending on the expected input. Why does it discards const qualifiers when I am using d on right hand side?
How do I fix the problem?


Thanks in advance!
The problem is that data is const and can't be modified. I often often avoid const data members but if you really want it you have to initialize it in the constructor.
1
2
3
4
S::S(const string& d)
:	data(d)
{
}
@peter87 my lecture said that pass by const is more memory efficient and is only supposed to be used when you don't need to alter the data you are passing. Apparently this saves a lot of time if you were executing a repetitious task thousands/millions of times per second.
@Blessman11 I have nothing against passing the argument as a const reference. What I was questioning was if S::data really should be const. I often find that it's more problem than it's worth having const members.
I thought I was initializing in the constructor itself.

I did not know that this code:

1
2
3
4
S::S(const string& d)
{
 data=d;
}

is different from
1
2
3
4
S::S(const string& d)
:	data(d)
{
}

@Peter I have to do this because I am trying to write a const iterator,I want to store the data structure as a const member.
Thanks for pointing it out. It did fix the problem!
Topic archived. No new replies allowed.