ProgrammingVery hardProduct-company placement · C++
Which lines fail to compile?
Which lines fail to compile?
struct H {
static H* make() { return new H; }
void destroy() { delete this; }
private:
~H() { }
};
int main() {
H h; // L1
H* p = H::make(); // L2
p->destroy(); // L3
delete p; // L4
}- A. L1 only
- B. L1 and L4
- C. L4 only
- D. L1, L3 and L4
Correct answer: B. L1 and L4
With a private destructor an automatic object (which must be destroyed at scope end) and an outside delete are both ill-formed. Members can still destroy it (delete this), which forces heap allocation through the class's own functions.
More OOP with C++ and Java questions
- 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…
- What is printed? java int[] arr = {1, 2, 3}; for (int x : arr) x = 2; System.out.print(Arrays.toString(arr));
- What is printed? java Set<String> s = new LinkedHashSet<>(List.of("a", "b", "c")); s.remove("a"); s.add("a"); s.add("b")…