I’ve run into this problem time & again, and I’ve always had to resolve it using a forward declaration and a pointer.
It seems wrong that C++ requires a work around to get objects to co-operate. Is there any way to get this to compile WITHOUT making Mesh* a pointer in class Shape (or, the vector<Tri> into vector<Tri*>?
Shape.h
#ifndef S
#define S
#include "Mesh.h"
//class Mesh ; //delete line above, uncomment this to make it work
class Shape // a mathematical shape
{
Mesh mesh ; // the poly mesh repr' this math shape
//Mesh *mesh ; // make it work
// a shape must be intersectable by a ray
//virtual Intersection intersects( const Ray& ray )=0 ;
} ;
#endif
Mesh.h
#ifndef M
#define M
#include <vector>
using namespace std;
#include "Triangle.h"
struct Mesh
{
vector<Triangle> tris ; // a mesh is a collection of triangles
} ;
#endif
Triangle.h
#ifndef T
#define T
#include "Shape.h"
class Triangle : public Shape
{
// a triangle must be intersectable by a ray
// a triangle's mesh is simple but it is still a mesh (1 poly)
} ;
#endif
It works for me without a pointer (there are, naturally, pointers used inside
std::vector). You just have to analyze your dependencies carefully.TriangleinheritsShape, thereforeShape‘s definition is aboveTriangle‘s.Shapecontains aMesh, thereforeMesh‘s definition precedesShape‘s. This gives the order:Mesh, Shape, Triangle, which compiles without errors.Naturally, some meshes will have to have empty vectors, since every triangle inside the vector itself requires a mesh.