Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Expanding on Q2, create a function that takes a Shape object by value and try to

ID: 3906478 • Letter: E

Question

  Expanding on Q2, create a function that takes a Shape object by value and try to upcast a derived object in as an argument. See what happens. Fix the function by taking a reference to the Shape object.   HERE IS Q2 #include <iostream>  using namespace std;  class Shape { public:     virtual void draw() = 0;   // pure virtual function }; class Circle : public Shape {     void draw()     {         cout << "Drawing Circle  ";     } }; class Square : public Shape {     void draw()     {         cout << "Drawing Square  ";     } };  class Triangle : public Shape {     void draw()     {         cout << "Drawing Triangle  ";     } }; int main() {      // creating pointers for base class     Shape* s[5];     // creating objects for child class     Circle* c = new Circle();     Square* sq = new Square();     Triangle* t = new Triangle();     // peforming upcasting     s[1] = c;     s[2] = sq;     s[3] = t;     // calling draw     s[1]->draw();     s[2]->draw();     s[3]->draw();      return 0; }

Explanation / Answer

#include <iostream>

using namespace std;

class Shape {
public:
    virtual void draw() = 0;   // pure virtual function
};
class Circle : public Shape {
    void draw()
    {
        cout << "Drawing Circle ";
    }
};
class Square : public Shape {
    void draw()
    {
        cout << "Drawing Square ";
    }
};

class Triangle : public Shape {
    void draw()
    {
        cout << "Drawing Triangle ";
    }
};

void draw_shape(Shape *s) {
   s->draw();
}

int main()
{

    // creating pointers for base class
    Shape* s[5];
    // creating objects for child class
    Circle* c = new Circle();
    Square* sq = new Square();
    Triangle* t = new Triangle();
    // peforming upcasting
    s[1] = c;
    s[2] = sq;
    s[3] = t;
    // calling draw
    draw_shape(s[1]);
    draw_shape(s[2]);
    draw_shape(s[3]);

    return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote