Question

Is it good practice to put the implementation of a pure virtual interface in a cpp and skip the header file completely?

A.h
struct A
{
    virtual void func() = 0;
};
B.cpp
class B : public A
{
   virtual void func() override {
   ...
   }
}
Was it helpful?

Solution

Somebody must use the class B, and they have to get instances of B from somewhere even if they only ever address them via an A*. So you could have for example:

A.h

struct A
{
    virtual void func() = 0;
    virtual ~A() {}
};

B.h

#include "A.h"
A *Bfactory();

B.cpp

#include "B.h"
struct B : public A { ... };
A *Bfactory() { return new B(); }

On the other hand, that's quite a "weak" factory function because it only ever returns instances of B. Perhaps there will be another factory function somewhere that creates different derived classes of A according to its parameters. That function would need to include A.h, B.h, C.h etc, but if it always uses Bfactory to create the instances of B then it doesn't need the class definition of B. So in that case it's fine for the class definition to only exist in B.cpp.

Btw, I've returned a raw pointer from the factory. In real life you might prefer to return a unique_ptr or other smart pointer. If you do so, then it is in fact possible to avoid the need for a virtual destructor in A. But I doubt that it's very often worth it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top