LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Predict the Output · Question 19

Copy assignment with a self-assignment check Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following C++ program?

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

class Note {
    std::string text_;
public:
    explicit Note(std::string t) : text_(std::move(t)) {}
    Note& operator=(const Note& o) {
        if (this == &o) { std::cout << "self "; return *this; }
        text_ = o.text_;
        std::cout << "copied ";
        return *this;
    }
    const std::string& text() const { return text_; }
};

int main() {
    Note a("buy milk"), b("call mom");
    a = a;
    b = a;
    std::cout << '\n' << a.text() << " | " << b.text() << '\n';
    return 0;
}
  • A self copied buy milk | buy milk Correct
  • B copied copied buy milk | buy milk
  • C self self buy milk | call mom
  • D copied buy milk | buy milk
Correct Answer: Option A

Comparing this with the address of the source detects a = a. For classes owning raw memory, skipping self-assignment prevents freeing the data before copying it.

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