See the rule of zero at work: with the right members, copying is correct without any extra code.
What to build
A Playlist class whose copies are independent, with no copy constructor written by hand.
Requirements
- Keep a name and a
vector<string>of songs as private members. - Make a copy of the playlist, rename the copy and add one song to it.
- Print the original and then the copy, to show that the original did not change.
Input
A name, then n, then n song titles, then the copy's new name, then the song to add. Names and titles are single words.
Output
Two lines, each NAME [K]: SONG SONG ..., for the original and then the copy.
Constraints
1 ≤ n ≤ 50.
Example
Input:
Morning
2
Intro Sunrise
Evening
Sunset
Output:
Morning [2]: Intro Sunrise
Evening [3]: Intro Sunrise Sunset
Why it works
The compiler's copy copies each member in turn, and string and vector make their own deep copies. So the copy owns separate songs, and changing it cannot affect the original.
Examples
Morning 2 Intro Sunrise Evening Sunset
Morning [2]: Intro Sunrise Evening [3]: Intro Sunrise Sunset
Gym 1 Pump Run Fast
Gym [1]: Pump Run [2]: Pump Fast
Hints
Hint 1
Store the songs in a `vector<string>` and the name in a `string`. Both copy themselves properly.
Hint 2
So `Playlist copy = original;` already makes a separate playlist, and you need no copy constructor.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Playlist {
string name;
vector<string> songs;
public:
Playlist(string n) : name(n) {}
void rename(string n) { name = n; }
void add(string song) { songs.push_back(song); }
void print() const {
cout << name << " [" << songs.size() << "]:";
for (const string& s : songs) cout << " " << s;
cout << endl;
}
};
int main() {
string name, song;
int n;
cin >> name >> n;
Playlist original(name);
for (int i = 0; i < n; i++) {
cin >> song;
original.add(song);
}
Playlist copy = original;
cin >> name >> song;
copy.rename(name);
copy.add(song);
original.print();
copy.print();
return 0;
}