Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected member conflict with overloading 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 is protected within this context

I thought that protected variables are accessible from the derived class under a public inheritance. What is causing this error?

like image 632
Stefan Rendevski Avatar asked Apr 26 '15 15:04

Stefan Rendevski


1 Answers

Derived can access protected members of Base on all instances of Derived only. But obj isn't an instance of Derived, it's an instance of Base - so access is forbidden. The following would compile fine, since now obj is a Derived

class Derived : public Base {
public:
    bool operator==(const Derived& obj) const {
        return myint == obj.myint;
    }
};
like image 185
Barry Avatar answered Nov 14 '22 21:11

Barry