LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 6

Error: assigning to an object with const members Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>
#include <string>

class Isbn {
    const std::string code_;
public:
    explicit Isbn(std::string c) : code_(std::move(c)) {}
    const std::string& code() const { return code_; }
};

int main() {
    Isbn a("978-0-13-235088-4"), b("978-1-49-190339-4");
    a = b;
    std::cout << a.code() << '\n';
    return 0;
}
  • A Isbn needs a destructor
  • B code_ is const, so the implicit copy assignment operator is deleted; immutable objects can be copied (Isbn c = b;) but not assigned Correct
  • C std::string cannot be const
  • D b must be const
Correct Answer: Option B

If assignment is needed, make the member non-const but private, with no setter – the class is still effectively immutable to its users.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links