LearnFrenzy
Sign in Take a free test

References: lvalue and rvalue · Reference Programs · Question 6

Class with reference-returning accessors in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write a Playlist class with a const accessor returning const std::string& and a non-const accessor returning std::string&, and show both in use.

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

class Playlist {
    std::vector<std::string> songs_;
public:
    void add(std::string s) { songs_.push_back(std::move(s)); }
    std::string& operator[](std::size_t i) { return songs_[i]; }               // editable
    const std::string& operator[](std::size_t i) const { return songs_[i]; }   // read-only
    std::size_t size() const { return songs_.size(); }
};

void print(const Playlist& p) {            // const object → const operator[] is used
    for (std::size_t i = 0; i < p.size(); ++i) std::cout << i + 1 << ". " << p[i] << '\n';
}

int main() {
    Playlist p;
    p.add("Kesariya");
    p.add("Tum Hi Ho");
    p[1] += " (Acoustic)";                 // modify through the returned reference
    print(p);
    return 0;
}

Output Verified by compiling and running

1. Kesariya
2. Tum Hi Ho (Acoustic)

The pair of overloads gives write access to non-const playlists and read-only access to const ones. add takes its parameter by value and moves it into the vector.

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