Jump to

v04-l3-checkAllowed

With the following class definition, what statement is allowed in the manipulate method ?

class A {
protected:
    double x;
};

class B : public A {
private:
    double x;
};

class C : public B {
    void manipulate(A& a, B& b){
        // ...
    }
};

???

Looking at the code again :

class A {
protected:
    double x;
};

class B : public A {
private:
    double x;
};

class C : public B {
    void manipulate(A& a, B& b){
        // ...
    }
};

and the possible answers :

  1. a.x = 1.0;
  2. b.x = 1.0;
  3. b.A::x = 1.0;

Since x is private in B, then b.x is naturally not allowed.

Now x is protected in A, which means that C (which inherits from A) can have access to it in its methods, but only for its current instance ! Furthermore, B redefines x with a private attribute, which means that the protected attribute A::B must be accessed explicitly with the scope resolution operator.

So we have :

class C : public B {
    void manipulate(A& a, B& b){
        a.x = 1.0       // NOPE ! a is not the current instance 
        b.A::x = 1.0    // NOPE ! b is not the current instance

        // Use 'this' to access the attribute of the current instance
        this->x = 1.0;       // NOPE ! A::x shadowed by private B::x
        this->B::x = 1.0;    // NOPE ! B::x is private
        this->B::A::x = 1.0; // OK    
    }
};