The class Book below has a const method - Author() - that returns the name of the book's author:
class Book {
public:
const std::string& Author() const {
if( author_.empty() ) {
// Lazy load
author_ = loadAuthorFromDb(); // ERROR !!
}
return author_;
}
//.. more public interface
private:
std::string author_;
//.... more data members
std::string loadAuthorFromDb() const;
};
As the author's name is not frequently accessed, we are loading it from database only if it is necessary. The method Author() does a one time lazy load of author's name from database when it is called the first time.
We are getting a compilation error when assigning to data member author_ because the method Author() is const. Which one of the following modifier keywords we should use for data member author_ to avoid this compilation error?