ProgrammingHardProduct-company placement · C++
What happens (C++14)?
What happens (C++14)?
struct S { static int n; };
int main() { S::n = 1; cout << S::n; }- A. It prints 1
- B. It compiles but fails to link: S::n is declared but never defined
- C. Compile-time error: static members cannot be assigned
- D. It prints 0
Correct answer: B. It compiles but fails to link: S::n is declared but never defined
The in-class line only declares a non-inline static data member; one translation unit must define it (int S::n;). Using it without a definition gives an 'undefined reference' at link time. C++17 inline static members avoid this.
More OOP with C++ and Java questions
- Which lines fail to compile? cpp void f(int) { cout << "I"; } void f(double) = delete; int main() { f(5); // L1 f('a'); // L2 f(2.5); //…
- Which lines fail to compile? cpp struct H { static H make() { return new H; } void destroy() { delete this; } private: ~H() { } }; int…
- What is printed? cpp struct B { virtual ~B() { } }; int main() { B p = nullptr; try { cout << typeid(p).name(); } catch (const badtypeid&)…
- What is printed? java class R implements AutoCloseable { String n; R(String n, boolean fail) { if (fail) throw new…
- What happens when this is compiled? java interface I { int f(); } abstract class A { abstract long f(); } class C extends A implements I {…
- What happens when this is compiled? java interface I { default void f() { System.out.print("I"); } } abstract class A { public abstract…