Home > Software design >  How to split definition and declaration with friend function and inheritance
How to split definition and declaration with friend function and inheritance

Time:11-23

I need to compile something like this:

struct Base {
    virtual void func1()=0;
    // ...
    friend void Derived::func2(Base *base);
private:
    int some_private;
}

struct Derived : Base {
    virtual func3()=0;
    // ...
    void func2(Base *child) {
        std::cout << child->some_private;
    }
};

But I keep getting compilation error. I tried swapping structures or declaring them first, but I can't declare Derived first (because of inheritance), and I can't declare Base first (because I need to declare friend function in Derived). What to do?

CodePudding user response:

You have a few basic solutions. The most obvious is to change from private to protected. In C , protected means subclasses have access.

You can add more public (perhaps protected) accessor methods instead.

You can forward-reference the entire Derived class and friend the entire class.

Personally, I have never felt a need to use friend methods or classes, and I don't know under what circumstances I'd have to be in before I wouldn't depend on other ways to accomplish whatever I'm trying to accomplish.

For this particular solution, I'd change the access to protected.

  • Related