// stringable.cpp
#include "cmpt_error.h"
#include <iostream>
#include <string>
using namespace std;
// Stringable is an abstract base class (ABC)
class Stringable {
public:
virtual string to_str() const = 0;
virtual ~Stringable() { }
};
class Window : public Stringable {
private:
string name;
int w; // width
int h; // height
public:
Window(const string& init_name, int init_w, int init_h)
: name(init_name), w(init_w), h(init_h)
{}
string to_str() const {
return "Window(" + name + ", "
+ to_string(w) + ", "
+ to_string(h) + ")";
}
}; // Window
// RGB color
class Color : public Stringable {
private:
int r = 0; // red, 0 to 255
int g = 0; // green, 0 to 255
int b = 0; // blue, 0 to 255
public:
Color() { } // default constructor
Color(int init_r, int init_g, int init_b)
: r(init_r), g(init_g), b(init_b)
{
if (r < 0 || r > 255) cmpt::error("red out of range");
if (g < 0 || g > 255) cmpt::error("green out of range");
if (b < 0 || b > 255) cmpt::error("blue out of range");
}
Color(const Color& other) // copy constructor
: Color(other.r, other.g, other.b)
{ }
int red() const { return r; }
int green() const { return g; }
int blue() const { return b; }
string to_str() const {
return "rgb(" + to_string(r) + ", "
+ to_string(g) + ", "
+ to_string(b) + ")";
}
}; // Color
struct Point : public Stringable {
double x = 0.0;
double y = 0.0;
Point() { }
Point(double a, double b)
: x(a), y(b)
{ }
string to_str() const {
return "(" + to_string(x) + ", "
+ to_string(y) + ")";
}
}; // Point
ostream& operator<<(ostream& out, const Stringable& s) {
out << s.to_str();
return out;
}
int main() {
Window w("Test", 100, 150);
cout << w << "\n";
Color c(100, 100, 120);
cout << c << "\n";
Point p{5, -2};
cout << p << "\n";
Point origin;
cout << origin << "\n";
}