LearnFrenzy
Sign in Take a free test

Operator Overloading · Operator Overloading Programs · Question 6

String builder using operator<< for chaining in C++ Solution, output & explanation

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

Write a Builder class whose operator<< accepts strings, numbers and characters (returning *this for chaining) and whose str() returns the result; build an invoice line and a CSV row.

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

class Builder {
    std::string s_;
public:
    Builder& operator<<(const std::string& x) { s_ += x; return *this; }
    Builder& operator<<(const char* x) { s_ += x; return *this; }
    Builder& operator<<(char c) { s_ += c; return *this; }
    Builder& operator<<(int n) { s_ += std::to_string(n); return *this; }
    const std::string& str() const { return s_; }
};

int main() {
    Builder line;
    line << "Item: " << std::string("Notebook") << " x " << 3 << " = Rs " << 3 * 60 << '!';
    Builder csv;
    for (int i = 1; i <= 4; ++i) (i > 1 ? csv << ',' : csv) << i * i;
    std::cout << line.str() << '\n' << csv.str() << '\n';
    return 0;
}

Output Verified by compiling and running

Item: Notebook x 3 = Rs 180!
1,4,9,16

Each operator<< returns the builder by reference, which is what makes chaining possible – exactly like std::ostream.

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