123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- // Trying to invoke the display function from a pointer, but
- // now display is virtual function.
-
- #include <iostream>
- using namespace std;
-
- class Shape {
- protected:
- int width, height;
- public:
- Shape() { width = height = 0; }
- Shape(int w, int h) { width = w; height = h; }
- virtual void display() const;
- };
-
- void Shape::display() const {
- cout << width << " " << height << endl;
- }
-
- class Rectangle : public Shape {
- public:
- Rectangle() {}
- Rectangle(int w, int h) : Shape(w, h) { }
- int perimeter() const;
- void display() const;
- };
-
- int Rectangle::perimeter() const{
- return 2 * width + 2 * height;
- }
-
- void Rectangle::display() const {
- cout << "I am rectangle of width " << width
- << " and height " << height << endl;
- }
-
- class Square: public Rectangle {
- public:
- Square() {}
- Square(int w) : Rectangle(w,w) {}
- void display() const;
- };
-
- void Square::display() const {
- cout << "I am square of side " << width << endl;
- }
-
-
- int main() {
-
- Shape *p;
- Shape *s;
- p = new Rectangle(4,8);
- s = new Shape(3,5);
-
- s->display();
- p->display();
-
- Shape *q = new Square(10);
- q->display();
-
- return 0;
- }
|