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
}
  1. A. L1 only
  2. B. L1 and L4
  3. C. L4 only
  4. 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

Exams that ask this topic