vendredi 1 mars 2019

friend overloaded operators of a derived class and base member access

I know that friend overloaded operators can access private members of the class they are friends with, but what are the rules when it comes to accessing the base class members of their friend?

I did some testing as seen below and found out that a friend overloaded operator of a derived class can access the protected member of a base class. Aren't friend functions not considered part of a class they are friends with, why are they able to access the protected members of a base class as if they are member functions of the derived class?

#include <iostream>
#include <string>

using namespace std;

class Animal {
    protected:
    string name;
    int age;

    public:
    Animal(string, int);
};

Animal::Animal (string n, int a) {
 name = n;
 age = a;
}

class Mouse : public Animal {

friend ostream& operator<< (ostream& out, const Mouse& obj);
private:
   double tailLength;
   double whiskersLength;

public:
   Mouse(string, int, double, double);
};

Mouse::Mouse (string n, int a, double t, double w) : Animal(n, a) {
    tailLength = t;
    whiskersLength = w;
}

ostream& operator<< (ostream& out, const Mouse& obj) {
    out << obj.name; //no error, why is this allowed?
    return out;
}

int main() {
    Mouse m1("nic", 2, 2.5, 3.5);
    cout << m1 << endl;
    cout << m1.name << endl; //error as expected

   return 0;
}

Aucun commentaire:

Enregistrer un commentaire