๐Ÿ“ข Too many exams? Donโ€™t know which one suits you best? Book Your Free Expert ๐Ÿ‘‰ call Now!

  • google app store apple app store
  • โœ–

      Question

      The following C++ code has a compilation error. How can

      you correct it to properly use the abstract base class `Printer`? #include class Printer { public: ย  ย  virtual void print() = 0; }; class LaserPrinter : public Printer { public: ย  ย  void print() { ย  ย  ย  ย  std::cout
      A The code is already correct; there is no error. Correct Answer Incorrect Answer
      B Change `virtual void print() = 0;` to `void print() {};`. Correct Answer Incorrect Answer
      C Remove the `override` keyword from `LaserPrinter::print()`. Correct Answer Incorrect Answer
      D Make `LaserPrinter` an abstract class. Correct Answer Incorrect Answer
      E Change `Printer* p = new LaserPrinter();` to `LaserPrinter* p = new LaserPrinter();`. Correct Answer Incorrect Answer

      Solution

      o The Printer class is correctly defined as an abstract base class because it has a pure virtual function print() (virtual void print() = 0;). o The LaserPrinter class correctly inherits from Printer and provides a concrete implementation for the print() method using override. This makes LaserPrinter a concrete (instantiable) class. o In main, Printer* p = new LaserPrinter(); demonstrates polymorphism. A pointer to the base class (Printer*) can point to an object of a derived class (LaserPrinter). This is perfectly valid and common practice in C++ for working with abstract classes. o The p->print(); call will correctly invoke LaserPrinter::print() due to virtual function dispatch. o delete p; correctly deallocates the dynamically allocated LaserPrinter object. o Therefore, the provided code is syntactically and logically correct and will compile and run without errors.

      Practice Next
      ask-question