Question: Consider the following C++ code: classWidget { public: virtual intf() {return1; } }; classGadget:publicWidget { public: virtual intf() {return2; } }; classGizmo:publicWidget { public: virtual

Consider the following C++ code:

classWidget {

public:

virtual intf() {return1; }

};

classGadget:publicWidget {

public:

virtual intf() {return2; }

};

classGizmo:publicWidget {

public:

virtual intf() {return3; }

};

voiddo_it(Widget *w) {

std::cout << w->f() <<" ";

}

intmain() {

std::vector widgets;

Widget wid;

Gadget gad;

Gizmo giz;

widgets.push_back(&wid);

widgets.push_back(&gad);

widgets.push_back(&giz);

for(size_t i = 0; i < widgets.size(); i++)

do_it(widgets[i]);

}

  1. What does the program print?

(b) Would the program still compile and run if the f method within the Widget class were a pure

virtual function?

(c) How would the program run differently if thevirtualkeyword were removed from all the

code?

(d) Would the program behave the same if thevirtualkeyword were removed from all the

classes except for Widget?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!