Bez popisu

inh05.cpp 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Trying to invoke the display function from a pointer, but
  2. // now display is virtual function.
  3. #include <iostream>
  4. using namespace std;
  5. class Shape {
  6. protected:
  7. int width, height;
  8. public:
  9. Shape() { width = height = 0; }
  10. Shape(int w, int h) { width = w; height = h; }
  11. virtual void display() const;
  12. };
  13. void Shape::display() const {
  14. cout << width << " " << height << endl;
  15. }
  16. class Rectangle : public Shape {
  17. public:
  18. Rectangle() {}
  19. Rectangle(int w, int h) : Shape(w, h) { }
  20. int perimeter() const;
  21. void display() const;
  22. };
  23. int Rectangle::perimeter() const{
  24. return 2 * width + 2 * height;
  25. }
  26. void Rectangle::display() const {
  27. cout << "I am rectangle of width " << width
  28. << " and height " << height << endl;
  29. }
  30. class Square: public Rectangle {
  31. public:
  32. Square() {}
  33. Square(int w) : Rectangle(w,w) {}
  34. void display() const;
  35. };
  36. void Square::display() const {
  37. cout << "I am square of side " << width << endl;
  38. }
  39. int main() {
  40. Shape *p;
  41. Shape *s;
  42. p = new Rectangle(4,8);
  43. s = new Shape(3,5);
  44. s->display();
  45. p->display();
  46. Shape *q = new Square(10);
  47. q->display();
  48. return 0;
  49. }