LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 16

Using a class built with the pimpl idiom Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

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

main.cpp
#include <iostream>
#include <memory>

class Counter {
    struct Impl;
    std::unique_ptr<Impl> p_;
public:
    Counter();
    ~Counter();
    void hit();
    int hits() const;
};

struct Counter::Impl { int hits = 0; int resets = 0; };

Counter::Counter() : p_(std::make_unique<Impl>()) {}
Counter::~Counter() = default;
void Counter::hit() { ++p_->hits; }
int Counter::hits() const { return p_->hits; }

int main() {
    Counter c;
    for (int i = 0; i < 4; ++i) c.hit();
    std::cout << c.hits() << ' ' << sizeof(c) << '\n';
    return 0;
}
  • A 4 8 Correct
  • B 4 16
  • C 4 4
  • D Compilation error
Correct Answer: Option A

All data lives in Impl on the heap; the Counter object itself is just one pointer (8 bytes on a 64-bit system), whatever Impl contains.

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