LearnFrenzy
Sign in Take a free test

Encapsulation · Encapsulation Programs · Question 9

Logger class using the pimpl idiom in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write a Logger class with the pimpl idiom: the header part shows only log(level, message), set_min_level and count; all state (messages, level, counters) lives in a hidden Impl struct.

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

// --- "logger.h" ---
class Logger {
public:
    enum Level { debug, info, error };
    Logger();
    ~Logger();
    void set_min_level(Level l);
    void log(Level l, const std::string& msg);
    int count() const;
private:
    struct Impl;
    std::unique_ptr<Impl> impl_;
};

// --- "logger.cpp" ---
struct Logger::Impl {
    Level min = info;
    std::vector<std::string> lines;
    static const char* tag(Level l) { return l == debug ? "DEBUG" : l == info ? "INFO " : "ERROR"; }
};

Logger::Logger() : impl_(std::make_unique<Impl>()) {}
Logger::~Logger() = default;
void Logger::set_min_level(Level l) { impl_->min = l; }
void Logger::log(Level l, const std::string& msg) {
    if (l < impl_->min) return;
    impl_->lines.push_back(std::string("[") + Impl::tag(l) + "] " + msg);
    std::cout << impl_->lines.back() << '\n';
}
int Logger::count() const { return static_cast<int>(impl_->lines.size()); }

// --- user code ---
int main() {
    Logger log;
    log.log(Logger::debug, "connecting");
    log.log(Logger::info, "server started");
    log.set_min_level(Logger::debug);
    log.log(Logger::debug, "cache warm");
    log.log(Logger::error, "disk full");
    std::cout << log.count() << " lines\n";
    return 0;
}

Output Verified by compiling and running

[INFO ] server started
[DEBUG] cache warm
[ERROR] disk full
3 lines

Users of Logger see no data members at all – adding a file sink or timestamps to Impl would not require recompiling them. The destructor is defined after Impl is complete, as unique_ptr requires.

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