12345678910111213141516171819202122232425262728293031323334353637383940 |
- // We have added a new member function (perimeter) to the
- // subclass Rectangle. Subclasses can have many more data members
- // and member functions besides the ones they inherit from their
- // base class.
-
- #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; }
- 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;
- };
-
- int Rectangle::perimeter() const{
- return 2 * width + 2 * height;
- }
-
- int main() {
- Rectangle r;
- Rectangle q(4,5);
- r.display();
- q.display();
- cout << "Perimeter of q is: " << q.perimeter() << endl;
- return 0;
- }
|