0

I have two classes. One depends on the other class and the other one contains a function that is friend to the first class. There's a lot of other stuff in this classes but this is what it boils down to:

class LightBase;

class Color
{
    friend void LightBase::UpdateColor();
};

class LightBase
{
    public:
        void UpdateColor();
    protected:
        std::vector<Color> colors_;
};

But apparently my forward declaration is not correct. I get this:

error: invalid use of incomplete type 'class LightBase'

I get that UpdateColor() is not known by the time the friend declaration is made. But how do I fix it?

rawrex
  • 4,044
  • 2
  • 8
  • 24
glades
  • 3,778
  • 1
  • 12
  • 34
  • 1
    You might do with the other order, `LightBase` just need declaration of `Color`, whereas `Color` need definition of `LightBase` (to know it has member `UpdateColor`). – Jarod42 Jul 30 '21 at 08:50

1 Answers1

2

It will work fine if you will change the arrangement a bit:

class Color;

class LightBase {
    public:
        void UpdateColor();
    protected:
        // Color has been declared
        std::vector<Color> colors_; 
};

class Color {
    // LightBase has been defined
    friend void LightBase::UpdateColor();
};

As to the use of LightBase::UpdateColor, we need to have LightBase class defined to use its function member LightBase, Since it is not known until then, as you pointed out yourself.

Meanwhile, we can have a std::vector<Color> with Color not being defined yet, only declared in the scope.

rawrex
  • 4,044
  • 2
  • 8
  • 24
  • Thanks, of course! How would I do it if LightBase befriended a function from Color? – glades Jul 30 '21 at 09:12
  • @glades You would have to declare the whole `Color` class as a friend. Check this [answer for elaboration](https://stackoverflow.com/questions/30623805/is-there-any-way-to-declare-mutual-friend-functions-for-two-classes). – rawrex Jul 30 '21 at 11:18