LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Predict the Output · Question 6

Copying a class whose members manage themselves Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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

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

struct Playlist {
    std::string name;
    std::vector<std::string> songs;
};

int main() {
    Playlist a{"road trip", {"song1", "song2"}};
    Playlist b = a;
    b.songs.push_back("song3");
    b.name += "!";
    std::cout << a.name << ' ' << a.songs.size() << " | " << b.name << ' ' << b.songs.size() << '\n';
    return 0;
}
  • A road trip 2 | road trip! 3 Correct
  • B road trip! 3 | road trip! 3
  • C road trip 3 | road trip! 3
  • D Compilation error
Correct Answer: Option A

The compiler-generated copy constructor copies each member, and std::string and std::vector make deep copies – the rule of zero in action.

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