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;
}
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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!