Search code examples
c++polymorphismfriend

Polymorphism with a friend function in C++


I would like to combine the concepts of polymorphism and friendship. I am making a pure virtual member function of a base class a friend of another class. I would then like to override this pure virtual member function in the classes derived from that base class, and access private member data of the class who has such function as friend. See the code snippet below. The compiler complains when I refer to my_int in the derived classes member function add(). I understand friendship is a 1-to-1 relationship, but I wonder if there is any way around it so as to implement polymorphism. Do I just have to make the member functions of the different derived classes friends of the foo() class?

class foo {
private:
    int my_int{};
public:
    friend virtual int base::add();
};

class base {
public:
    virtual int add() = 0;
};

class derived_1 : public base {
public:
    int add() {
        return my_int + 1;
    }
};

class derived_2 : public base {
public:
    int add() {
        return my_int + 2;
    }
}

Solution

  • First, with what you've displayed it's not going to work because my_int is a member of foo but in the base class tree there is no 'foo' to get the member from.

    The easy answer would be to make the function take an int argument and do away with the use of friend entirely.

    struct derived2 : base
    {
      int add(int arg) { return arg + 2; }
    };
    

    The use of 'friend' should make you seriously question whether what you are doing is a good answer, sometimes the answer to that question is 'yes' but not often. And the more friends you need the less often the answer remains 'yes'.

    Another way would be to add a function to base:

    int get_arg(foo & f) { return f.my_int; }
    

    and make that function the friend rather than add, get_arg() would be called from each derived's add() in order to get the value to work with but get_arg is not itself virtual.