0

Why this won't compile? What am I missing?

class Base
{
    public:
        Base() : data(0) { }
    protected:
        int data;
};

class Derived : public Base
{
    public:
        Derived() : Base() { }
        Derived& operator=(const Base& _base)
        {
            data = _base.data; // protected member Base::data is not accessible through a "Base" pointer or object.
        }
};

Why is that, since data member has protected visibility (so that derived classes can access it).

Zereges
  • 5,139
  • 1
  • 25
  • 49
  • 5
    `protected` doesn't mean you can access the member from any `Base`, but only from `Derived::Base` - a `Base` base class subobject of `Derived` object. There might be another class, say `X`, derived from `Base`, that uses `data` differently than `Derived` does. `Derived` shouldn't be allowed to mess with the internals of another, unrelated class. – Igor Tandetnik Jan 01 '15 at 16:23
  • 1
    What you should do to fix your code is to delegate to `Base::operator=`, rather than accessing `Base` members directly. – Igor Tandetnik Jan 01 '15 at 16:26
  • Can't you use a `friend` function? – alacy Jan 01 '15 at 16:54

0 Answers0