Protected participant conflict with overload operator

I have the following classes:

class Base {
protected:
    int myint;        
};

class Derived : public Base {
public:
    bool operator==(Base &obj) {
        if(myint == obj.myint)
            return true;
        else
            return false;
    }
};

But when I compile it, it gives the following errors:

int Base::myint protected in this context

I thought that protected variables are accessible from a derived class under common inheritance. What causes this error?

+5
source share
1 answer

Derivedcan access protected members Basefor all instances only Derived. But objit is not an instance Derived, it is an instance Base- therefore access is denied. The following will compile fine, as it objis nowDerived

class Derived : public Base {
public:
    bool operator==(const Derived& obj) const {
        return myint == obj.myint;
    }
};
+7
source

Source: https://habr.com/ru/post/1584746/


All Articles