2

The following struct should hold a shared_ptr to an abstract base class (Shape). However, when I try to write this, I get error C2065: 'Shape' : undeclared identifier.

So I know that I can't create instances of Shape, only instances of the derived Spheres, Boxes, etc. But why can't I use a shared_ptr to an abstract base class?

#include <memory>  // std::shared_ptr

#include "shape.hpp"

struct Hit {
    // …

    std::shared_ptr<Shape> m_shape;  // Shape that was hit
};

It should be noted that indeed the Shape class is using the Hit struct and vice versa.

kleinfreund
  • 6,546
  • 4
  • 30
  • 60

1 Answers1

6

Replace #include "shape.hpp" in the above with the forward declaration

class Shape; (you might need struct Shape; depending on how Shape is declared).

This is possible since class members of type std::shared_ptr can be declared with an incomplete type.

This helps you to untangle circular inclusions. Of course, the source file that defines the functions for struct Hit will need to #include shape.hpp.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483