Comp 2673, Spring 2002
April 19, lecture notes
Reading: Begin reading D&D, chapter 9 Now we begin learning new features of the C++ language - Inheritance and polymorphism are two important capabilities of object-oriented programming. - The idea of inheritance is to create new classes out of existing classes. - If you want to use an existing class, but it's missing some attributes or behaviors that you need, you can create a new class by starting with the original one, and embellishing it with new attributes and behaviors or overriding existing behaviors. - The original class (that you build on top of) is called the base class, and the new one is called the derived class. - A derive class is a class in its own right, so you can derive yet a new class from it. This gives a hierarchy of classes. - An example that you've already seen is ostream and ofstream. ofstream is derived from the base class ostream. This means that an ofstream object is a special case of an ostream object. (In fact, there is a hierarchy of classes that ostream and ofstream are part of - see page 761 of D&D for more details on this.) - You can derive a class from multiple classes at once. This is called multiple inheritance and we will not study it. Example and syntax: // base class Class Shape { public: Shape(float x=0, float y=0); Shape(const Shape &); void display() const; float get_xpos() const {return ypos;} float get_ypos() const {return xpos;} void move(float x_trans, float y_trans); // translate by given distance void resize(float scale); // changes size by factor scale protected: float x_pos; // x coordinate of the center of the shape float y_pos; // y coordinate of the center of the shape }; Class Square : public Shape { public: Square(float s=0, float x=0, float y=0); Square(const Square &); void set_side(float s) {if (s >= 0) side = s; else side=0;} float get_side() const {return side;} float area() const {return side*side;} float perimeter() const {return 4*side}; private: float side; // length of the side of the square };