xfbs
xfbs

Reputation: 177

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

Just a little warning: I've only been doing C++ for 2 weeks now, expect to see stupid beginner errors.

I was writing some (useless) code to get familiar with classes in C++ (it's a wrapper around a string), and I added a copy constructor, but I keep on getting this 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’ as ‘this’ argument of ‘const std::string CValue::getData()’ discards qualifiers
make: *** [val] Error 1

I have done research, apparently this error is caused by the copy constructor doing non-const operations. I get that much. In response, I made CValue::getData() a const member. Apart from accessing getData(), the copy constructor doesn't do anything, so I don't see why I am still getting the error. Here is (some of) the 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 anyone know what I'm doing wrong? Cause I have no idea. Thanks in advance, and I guess I'm buying a proper C++ book to get started properly.

Upvotes: 2

Views: 1057

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Instead of

const string getData();

try

string getData() const;

Your version makes the return string const, not the method.

Upvotes: 6

Björn Pollex
Björn Pollex

Reputation: 76838

You need to make getData a const-method:

 const string CValue::getData() const {
     return *value;
 }

Also, as your class looks now, it is not necessary to make value a pointer. Just make it a member-object.

Upvotes: 4

Related Questions