Reputation: 49
These snippets of code are pretty short, but I can't understand what I am missing with the const keyword. In my first snippet, when I put const after the function definition it says that just returning something disqualifies the const keyword:
string & getText() const {
return txt;
}
jdoodle.cpp: In member function 'std::__cxx11::string& Document::getText() const': jdoodle.cpp:29:16: error: binding 'const string {aka const std::__cxx11::basic_string}' to reference of type 'std::__cxx11::string& {aka std::__cxx11::basic_string&}' discards qualifiers return txt; ^
And the second, when I simply put return a; instead of return *this; I end up with a violation of the const keyword.
File & operator = (const File & a) {
this->drive = a.drive;
this->folder = a.folder;
this->fileName = a.fileName;
this->txt = a.txt;
this->fullPath = a.fullPath;
return a;
}
jdoodle.cpp: In member function 'File& File::operator=(const File&)': jdoodle.cpp:117:16: error: binding 'const File' to reference of type 'File&' discards qualifiers return a; ^
And finally, the third (when I put in the actual mutators like now, it throws the violation error--unlike when I just put the member variables):
File & File::operator = (File & a) {
this->getDrive() = a.getDrive();
this->getFolder() = a.getFolder();
this->getFileName() = a.getFileName();
this->getText() = a.getText();
this->fileName = a.fileName;
return a;
}
Upvotes: 2
Views: 346
Reputation: 41760
When making as assignment operator, you probably want to return *this
.
With that said, you still got an error about your getter function discarding qualifiers.
Even if I'd advise you to use members directly in your assignment operator, here's how you can fix the code.
Your getter functions might look like this:
string& getText() {
return txt;
}
You will need to provide an additional overload for const objects:
const string& getText() const {
return txt;
}
The difference here is that this
, and every member are const
in a const qualified function. Since you want to return a reference to that string, which is more const, you need to return a const reference.
By providing the const and the non-const version, you will still be able to mutate object returned by your getter, and having an additional overload will make non mutable getters to work with non mutable objects.
Upvotes: 1