LearnFrenzy
Sign in Take a free test

Inheritance · Inheritance Programs · Question 7

GUI widget hierarchy with base and derived drawing in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Write a Widget base (position and draw_frame) and derived Button and TextBox classes whose render() call the base frame drawing and then add their own content.

Solution
main.cpp
#include <iostream>
#include <string>

class Widget {
protected:
    int x_, y_;
    std::string id_;
    void draw_frame(int width) const {
        std::cout << id_ << " @(" << x_ << ',' << y_ << ") +" << std::string(width, '-') << "+\n";
    }
public:
    Widget(std::string id, int x, int y) : x_(x), y_(y), id_(std::move(id)) {}
};

class Button : public Widget {
    std::string text_;
public:
    Button(std::string id, int x, int y, std::string t) : Widget(std::move(id), x, y), text_(std::move(t)) {}
    void render() const {
        draw_frame(static_cast<int>(text_.size()) + 2);
        std::cout << "    | " << text_ << " |\n";
    }
};

class TextBox : public Widget {
    std::string value_;
    int width_;
public:
    TextBox(std::string id, int x, int y, int w) : Widget(std::move(id), x, y), width_(w) {}
    void type(const std::string& s) { value_ += s; }
    void render() const {
        draw_frame(width_);
        std::cout << "    |" << value_ << std::string(width_ - value_.size(), ' ') << "|\n";
    }
};

int main() {
    Button ok("btnOk", 10, 20, "Submit");
    TextBox name("txtName", 10, 5, 12);
    name.type("Asha");
    name.render();
    ok.render();
    return 0;
}

Output Verified by compiling and running

txtName @(10,5) +------------+
    |Asha        |
btnOk @(10,20) +--------+
    | Submit |

The shared position and frame-drawing logic live once in the base class; draw_frame is protected because only widgets should call it. Each derived class adds its own content after the frame.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links