Calling Protected Function From Derived Friend Function

149 views Asked by At

I have a base class, Animal, and a derived class, Lion. Animal has a protected function called eat(). I would like to call eat() from a friend function defined in Lion, but when it won't compile:

error: call to non-static member function without an object argument

Why can't I call a protected function from a friend of Lion? I have work-arounds, but I can't figure out why a friend wouldn't be able to call eat(). It doesn't seem to matter if I use Animal::eat or Lion::eat, I get the same error. Thoughts?

#include <iostream>
using namespace std;

class Animal{
public:
    Animal(int m) : mass(m){}
    int getMass() const { return mass; }
protected:
    int mass;
    void eat(const Animal& lhs, const Animal& rhs, Animal *result){
        result->mass = lhs.getMass() + rhs.getMass();
    }
};

class Gazelle : public Animal{
public:
    Gazelle(int m) : Animal(m){}
};

class Lion : public Animal{
public:
    Lion(int m) : Animal(m){}

    friend Lion feed(const Lion &lhs, const Gazelle &rhs){
        Lion hungry(0);
        eat(lhs, rhs, &hungry);
        return hungry;
    }
};

int main(void){
    Lion leo(5);
    Gazelle greg(1);

    Lion fullLeo = feed(leo, greg);
    cout << "Full Leo has mass " << fullLeo.getMass() << endl;
}
1

There are 1 answers

1
Pratap On BEST ANSWER

A friend function is a non member function which has access to private members of a class. But you still have to provide the object details for accessing data members.

The usage of eat function must be similar to object_name.eat() in the feed function.