3

I have a problem with my classes.

I have two separate headers. Color.h and Painter.h:

1). Color.h

class Color{
       int number;
    public:
       void initialize();
       void change (Painter draw);
}

2). Painter.h

class Painter{
      Color a,b;
   public:
      void get();
      void draw();
}

My problem is, that i need to use Painter in class Color, and class Painter use Color. In Qt, i get a error that Painter is not a type. How can i fix this? What is solution for that problem?

CROmpir
  • 33
  • 3
  • 3
    You can make that happen by forward declaring one class in the other and use only pointers to the forward declared class. But if you have circular dependencies in such a simple case, consider changing the design of your software – Simon Warta Dec 23 '14 at 23:21

1 Answers1

3

In Painter.h you need to include Color.h, because you have objects of type Color. But in color.h you can add a forward declaration for the Painter class:

class Painter;
class Color{
   int number;
public:
   void initialize();
   void change (Painter draw); //a forward declaration is enough for this
}

And the method void change (Painter draw); you will define it in the color.cpp and there you include painter.h

Zlatomir
  • 6,964
  • 3
  • 26
  • 32
  • Don't you need to change `void change (Painter draw);` to `void change (Painter & draw);` for this to work? – drescherjm Dec 23 '14 at 23:29
  • 1
    @drescherjm I was thinking about that too, but it looks okay (http://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration) – Simon Warta Dec 23 '14 at 23:30
  • 1
    @Zlatomir: that is incorrect explanation: `because you don't construct an object there`. You do not need it, but not because of that as you do not construct the base class in the header either, yet you need it. – László Papp Dec 24 '14 at 00:26