ProgrammingModerateProduct-company placement · C++
Which line fails to compile?
Which line fails to compile?
struct P {
int v = 1;
int get() { return v; }
int cget() const { return v; }
};
int main() {
const P p{};
cout << p.cget(); // L1
cout << p.get(); // L2
cout << p.v; // L3
}- A. L1 only
- B. L2 and L3
- C. None
- D. L2 only
Correct answer: D. L2 only
On a const object only const member functions can be called, because this is a pointer to const. Reading a data member is fine; get() is not marked const.
More OOP with C++ and Java questions
- Which lines fail to compile? cpp struct S { int x = 1; static int y; static int f() { return y; } // L1 static int g() { return x; } // L2…
- Which lines fail to compile? cpp struct B { virtual void f(int) { } virtual void g() const { } void h() { } }; struct D : B { void f(int)…
- Which lines fail to compile? cpp struct B { virtual void f() final { } virtual void g() { } }; struct D : B { void f() { } // L1 void g()…
- What is printed? cpp struct B { virtual ~B() { } }; struct D : B { }; struct E : B { }; int main() { B p = new D; cout <<…
- What is printed? cpp struct A { }; struct B : A { }; struct P { virtual ~P() { } }; struct Q : P { }; int main() { B b; Q q; A& ra = b; P&…
- What is printed? cpp struct A { A(int x) { cout << x; } A() { cout << 0; } }; struct B : virtual A { B() : A(1) { cout << "B"; } }; struct…