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
};- A. Line 2
- B. Line 3
- C. Line 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
- What is printed? cpp int main() { auto a = makeshared<int>(1); auto b = a; { auto c = b; cout << a.usecount(); } weakptr<int> w = a; cout…
- What is printed? cpp void f(int) { cout << "i"; } void f(char) { cout << "c"; } void f(double) { cout << "d"; } int main() { char a = 'a'…
- Which statement about this code is correct? cpp struct B { virtual void f() const { } }; struct D : B { void f() override { } };
- What is printed? cpp struct B { int x = 5; }; struct D : B { int x = 7; }; int main() { D d; B& b = d; cout << d.x << b.x << d.B::x; }
- What is printed? java class P { String f = "P"; static String s() { return "P"; } String i() { return "P"; } } class C extends P { String…
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("L"); } static void f(Integer x) {…