LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 10

Error: using pimpl members where Impl is incomplete Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

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

class Engine {
public:
    struct Impl;
    Engine();
    ~Engine();
    int rpm() const { return impl_->rpm; }
private:
    std::unique_ptr<Impl> impl_;
};

struct Engine::Impl { int rpm = 800; };
Engine::Engine() : impl_(std::make_unique<Impl>()) {}
Engine::~Engine() = default;

int main() {
    Engine e;
    std::cout << e.rpm() << '\n';
    return 0;
}
  • A unique_ptr cannot hold Impl
  • B rpm() is defined inline in the class, where Impl is still incomplete, so impl_->rpm cannot be accessed; define rpm() after Impl is complete (in the .cpp) Correct
  • C Impl must be private
  • D The destructor must be virtual
Correct Answer: Option B

With pimpl, every member function that touches Impl must be defined where Impl's definition is visible – normally the .cpp file.

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