ProgrammingVery hardMicrosoft/Amazon SDE MCQ · GATE CS

Which line fails to compile?

Which line fails to compile?
class B { protected: int v = 1; };
class D : public B {
public:
    int me()           { return v; }        // line 1
    int peek(B& b)     { return b.v; }      // line 2
    int peekD(D& d)    { return d.v; }      // line 3
    int up(D& d)       { return d.B::v; }   // line 4
};
  1. A. Line 2
  2. B. Line 3
  3. C. Line 4
  4. D. None of them

Correct answer: A. Line 2

In C++ a derived class may access a protected member only through an object of its own type (or further derived). b is a B&, so b.v is an error; d.v and d.B::v go through a D, and v is through this.

More OOP with C++ and Java questions

Exams that ask this topic