Created
March 23, 2022 04:24
-
-
Save JustinStitt/4e9ce099afe7009b931276aba8c8116e to your computer and use it in GitHub Desktop.
Sorta? shows polymorphism in cc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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