1
class B
{ 
  protected:
    int x;
  public: 
    B(int i=28) { x=i; }
    virtual B f(B ob) { return x+ob.x+1; }
    void afisare(){ cout<<x; }
};
class D: public B
{
  public:
    D(int i=-32):B(i) {}
    B f(B ob) { return x+ob.x-1; }
};

void test6()
{
  B *p1=new D, *p2=new B, *p3=new B(p1->f(*p2));
  p3->afisare();
}

The main just calls the function test6(); My question is, why does the compiler throw an error on the 3rd line, at int x declaration, with the message :

In member function 'virtual B D::f(B)' : 
error: 'int B::x' is protected 
error: within this context

PS : The example is from an exam so the faulty indentation and other "leaks" are intentionally.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64

1 Answers1

1

D can access B's member x but only the one it inherits. It cannot access member x of another instance of B.

EDIT: Corrected the answer.

Inline
  • 2,566
  • 1
  • 16
  • 32
  • 1
    `D::f()` can access `B::x` inside any object of type `D`, not just `*this`. For example, `D::f(D other) { return x + other.x - 1; }` is perfectly fine. – Ben Voigt Jun 12 '16 at 16:37
  • @BenVoigt , thanks, I corrected the answer. – Inline Jun 12 '16 at 16:45