summaryrefslogtreecommitdiffstats
path: root/abstract.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'abstract.cpp')
-rw-r--r--abstract.cpp74
1 files changed, 74 insertions, 0 deletions
diff --git a/abstract.cpp b/abstract.cpp
new file mode 100644
index 0000000..99edd52
--- /dev/null
+++ b/abstract.cpp
@@ -0,0 +1,74 @@
+#include <iostream>
+#include <string>
+
+/* below tweak needs to know wbout this class */
+template <class T>
+class Polygon;
+
+/* convine the compiler that overloaded operators are templates themselves before
+ * we reach the declaration of the class */
+template <class T>
+std::ostream& operator<<(std::ostream &, const Polygon<T> &);
+
+template <class T>
+class Polygon
+{
+ public:
+ /* notice the <> after function name, we're letting g++ know this is a template */
+ friend std::ostream& operator<<<>(std::ostream &, const Polygon<T> &);
+
+ /* pure virtual, subclass must DEFINE it. otherwise that subclass itself
+ * will remain abstract and won't be able to be instantiated */
+ virtual T area(void) = 0;
+
+ T getWidth(void) {
+ this->width;
+ }
+
+ T getHeight(void) {
+ this->height;
+ }
+
+ protected:
+ T width, height;
+ std::string type; /* name of polygon */
+};
+
+template <class T>
+class Triangle : public Polygon<T>
+{
+ public:
+ Triangle() {
+ this->width = 0;
+ this->height = 0;
+ this->type = std::string("triangle");
+ }
+
+ Triangle(int b, int h) {
+ this->width = b;
+ this->height = h; /* this keyword has to be used? */
+ this->type = std::string("triangle");
+ }
+
+ virtual T area(void) {
+ return (this->width * this->height) / 2;
+ }
+};
+
+template <class T>
+std::ostream& operator<<(std::ostream& stream, const Polygon<T>& p)
+{
+ stream << p.type << " dimensions, width: " << p.width << ", height: " << p.height
+ << ", area: "<< const_cast<Polygon<T> *>(&p)->area(); /* lol at the cast! */
+
+ return stream;
+}
+
+int main(int argc, char *argv[])
+{
+ Triangle<int> tri(6, 4);
+ std::cout << tri << std::endl;
+
+ return 0;
+}
+