1

I've started using C++ recently. I understand that access modifiers are class-based and not instance-based, like some other questions point out.

However, this example seem to contraddict this:

class Parent {
protected:
    int _attr = 1;
};

class Child: public Parent {
    Parent *other_instance;
public:
    Child(): other_instance(new Parent()) {}

    int bar() {
        return _attr;
    }

    int foo() {
        return other_instance->_attr;
    }
};

int main() {
    Child c;
    c.foo();
}

My compiler (g++ (GCC) 5.2.0) complains over the access :

test.cpp: In member function ‘int Child::foo()’:
test.cpp:4:17: error: ‘int Parent::_attr’ is protected
     int _attr = 1;
                 ^
test.cpp:17:32: error: within this context
         return other_instance->_attr;

Why does this not work?

Community
  • 1
  • 1
Davide
  • 2,104
  • 2
  • 15
  • 17

0 Answers0