Skip to content

Instantly share code, notes, and snippets.

@JustinStitt
Created March 23, 2022 04:24
Show Gist options
  • Save JustinStitt/4e9ce099afe7009b931276aba8c8116e to your computer and use it in GitHub Desktop.
Save JustinStitt/4e9ce099afe7009b931276aba8c8116e to your computer and use it in GitHub Desktop.
Sorta? shows polymorphism in cc
#include <bits/stdc++.h>
struct Shape {
virtual double area() {
std::cout << "I am a Shape\n";
return 0.0;
}// non-pure virtual
};
struct Rectangle : public Shape {
int w, h;
Rectangle(int _w, int _h) : w(_h), h(_h) {}
double area() { // override
std::cout << "I am a Rectangle: \n";
return this->w * this->h;
}
};
struct Triangle : public Shape {
int w, h;
Triangle(int _w, int _h) : w(_h), h(_h) {}
double area() { // override
std::cout << "I am a Triangle: \n";
return (this->w * this->h) / 2;
}
};
int main() {
std::vector<Shape*> shapes; // mro (method resolution order)
Rectangle* r1 = new Rectangle(3, 4);
Shape* t1 = new Triangle(5, 11);
Shape* s1 = new Shape;
shapes.push_back(r1);
shapes.push_back(t1);
shapes.push_back(s1);
for(Shape* s : shapes) {
std::cout << "Area = " << s->area() << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment