0

This is a piece of code I found in an example in one of my OOP courses. When I try to compile it I get the following error:

'A::x' : cannot access protected member declared in class 'A'.

Because of inheritance, shouldn't B be able to access A's protected int?

#include<iostream>
using namespace std;

class A
{
protected: int x;
public: A(int i = -16) { x = i; }
        virtual A f(A a) { return x + a.x; }
        void afisare() { cout << x; }
};

class B : public A
{
public: B(int i = 3) :A(i) {}
        A f(A a) { return x + a.x + 1; }
};

int main()
{
    A *p1 = new B, *p2 = new A, *p3 = new A(p1->f(*p2));
    p3->afisare();
    system("Pause");
}
Shury
  • 468
  • 3
  • 15
  • 49

1 Answers1

6

B can access A's member x but only the one it inherits. It cannot access member x of another instance of A (a.x in f).

StenSoft
  • 9,369
  • 25
  • 30