c++ - Why am I getting a g++ error about discarding qualifiers in my code when compiling? -


just little warning: i've been doing c++ 2 weeks now, expect see stupid beginner errors.

i writing (useless) code familiar classes in c++ (it's wrapper around string), , added copy constructor, keep on getting error:

pelsen@remus:~/dropbox/code/c++/class-exploration> make val g++ -o val.o val.cpp val.cpp: in copy constructor ‘cvalue::cvalue(const cvalue&)’: val.cpp:27: error: passing ‘const cvalue’ ‘this’ argument of ‘const std::string cvalue::getdata()’ discards qualifiers make: *** [val] error 1 

i have done research, apparently error caused copy constructor doing non-const operations. much. in response, made cvalue::getdata() const member. apart accessing getdata(), copy constructor doesn't anything, don't see why still getting error. here (some of) buggy code:

  7 class cvalue {   8   string *value;   9 public:  10   cvalue();  11   cvalue(string);  12   cvalue(const cvalue& other);  13   ~cvalue();  14   void setdata(string);  15   const string getdata();  16 };  17   22 cvalue::cvalue(string data) {  23   value = new string(data);  24 }  25   26 cvalue::cvalue(const cvalue& other) {  27   value = new string(other.getdata());  28 }  37   38 const string cvalue::getdata() {  39   return(*value);  40 } 

does know i'm doing wrong? cause have no idea. in advance, , guess i'm buying proper c++ book started properly.

you need make getdata const-method:

 const string cvalue::getdata() const {      return *value;  } 

also, class looks now, not necessary make value pointer. make member-object.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -