A Destructive Relationship
Test your C++ programming skills by solving the given puzzle about destructors and virtual functions.
We'll cover the following
Puzzle code
Carefully read the code given below:
#include <iostream>#include <memory>struct Widget{virtual void draw() { std::cout << "Widget draw\n"; }virtual ~Widget() { std::cout << "Widget destructor\n"; }};struct Button : public Widget{void draw() override { std::cout << "Button draw\n"; }~Button() override { std::cout << "Button destructor\n"; }};int main(){std::unique_ptr<Widget> widget = std::make_unique<Button>();widget->draw();}
Your task: Guess the output
Try to guess the output of the above code. Attempt the following quiz to assess your understanding.
Q
What is the expected output of the above code?
A)
Widget draw
Button draw
Button destructor
Widget destructor
B)
Button draw
Button destructor
Widget destructor
C)
Widget draw
Button destructor
Widget destructor
D)
Button draw
Button destructor
Let’s discuss this code and output together in the next lesson.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.