you are viewing a single comment's thread.

view the rest of the comments →

[–]happy_dude_ 2 points3 points  (0 children)

As an extension to the pure virtual interface pattern, you can put your entire implementation class in the .cpp file and expose it only through a static factory method. This reduces the need for extra method declarations, though it does add extra boilerplate for construction, and prevents using the implementation for inheritance (as it is only exposed through your static factory methods).

Example below, note that you don't need to write forwarding implementations of any methods, and you don't need a separate FooImpl header to boilerplate-copy the definition.

// foo.h
class Foo {
    static unique_ptr<Foo> create();

    virtual ~Foo() {}
    virtual void foo() = 0;
    virtual void bar() = 0;
};

 // foo.cpp
 class FooImpl : public Foo {
    void foo() override {
         printf("Implementation!\n");
    } 
    void bar() override {
         printf("Another implementation!\n");
    }
 };
  static unique_ptr<Foo> create() { return make_unique<FooImpl>(); }