Skip to content

Instantly share code, notes, and snippets.

@kenpower
Created February 9, 2024 10:25
Show Gist options
  • Save kenpower/ae9bd5494d4b1c7a918c13805f709973 to your computer and use it in GitHub Desktop.
Save kenpower/ae9bd5494d4b1c7a918c13805f709973 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <vector>
class Drawable {
public:
virtual void draw() const = 0;
};
class Shape : public Drawable {
protected:
int x, y;
public:
Shape(int x, int y) : x(x), y(y) {}
virtual void draw() const = 0;
};
// Derived classes
class Circle : public Shape {
private:
int radius;
public:
Circle(int x, int y, int radius) : Shape(x, y), radius(radius) {}
void draw() const override {
std::cout << "Drawing a circle at (" << x << ", " << y << ") with radius " << radius << std::endl;
}
};
class Rectangle : public Shape {
private:
int width, height;
public:
Rectangle(int x, int y, int width, int height) : Shape(x, y), width(width), height(height) {}
void draw() const override {
std::cout << "Drawing a rectangle at (" << x << ", " << y << ") with width " << width << " and height " << height << std::endl;
}
};
class Picture {
private:
std::vector<const Shape*> shapes;
public:
void addShape(const Shape* shape) {
shapes.push_back(shape);
}
void drawAll() const {
for (const auto& shape : shapes) {
shape->draw();
}
}
};
class Car { // draws a simpified car
private:
Circle wheelFront;
Circle wheelRear;
Rectangle body;
public:
Car(int x, int y) :
wheelFront(x-5, y+5, 10),
wheelRear(x+5, y+5, 10),
rectangle(x-10, y-5, x+10, y+5,) {}
void draw() const {
wheelFront.draw();
wheelRear.draw();
body.draw();
}
};
int main() {
// Creating objects
Circle circle(5, 5, 10);
Rectangle rectangle(10, 10, 20, 30);
Picture picture;
// Adding shapes to drawing
picture.addShape(&circle);
picture.addShape(&rectangle);
// Drawing all shapes
picture.drawAll();
Car car(0, 0);
car.draw();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment