0

Sometimes during class designing I have an issue with class organization. For example I have an Shape class that is abstract base class for all type of shapes: rectangles, polygons, circles, etc:

Shape.h:

#pragma 

class Rectangle;

class Shape {
    public:
        Shape();
        ...

        virtual Rectangle boundingRectangle() const = 0;
};

And I have an Rectangle class derived from Shape:

Rectangle.h:

#pragma once

#include "Shape.h"

class Rectangle : public Shape {
    public:
        Rectangle();
        ...

        Rectangle boundingRectangle() const;
};

The obvious problem using such method is that I can't forward declare Rectangle in Shape.h. The only solution I know is to declare Rectangle right after Shape in Shape.h and in Rectangle.h include Shape.h (for example see QGeoShape and QGeoRectangle here).

Solution above has some disadvantages when you need to use several classes inherited from Shape (For example virtual Circle Shape::boundingCircle() const) in Shape class declaration. Maybe someone know another solution?

Kamil Zaripov
  • 904
  • 11
  • 33
  • 1
    You can, and you did, declare `Rectangle` before `Shape` in `Shape.h`. What is the problem? – Quentin Feb 09 '17 at 16:01
  • 1
    @Quentin the problem is a compile time error. Forward declaring Rectangle is enough to pass it by reference or pointer, but if it's passed/returned by value then the compiler needs to know its size. – PeterT Feb 09 '17 at 16:02
  • 1
    You can use forward declarations only as references or pointers. – πάντα ῥεῖ Feb 09 '17 at 16:02
  • 1
    @PeterT Incomplete types can be used as parameters and return values in declarations without issue, see [this demo](http://coliru.stacked-crooked.com/a/a1d631f91f3d9ceb). – Quentin Feb 09 '17 at 16:06
  • Yes, correct, my mistake. – Kamil Zaripov Feb 09 '17 at 16:11

0 Answers0