Programming and Graphics

(Kiana) #1

6.14 Inheritance 187


Roses are flowers


Next, we define the derived class of roses, which can be either garden or
long-stem roses. The rose class definition is:


class rose : public flower
{
public:
rose(string, string, string, float); // parametered constructor
void print() const;
private:
string rosetype;
};

Since roses derive from flowers, there is no need to repeat the flower attributes or
functions, and we simply add to them. The rose class implementation includes
the parameter constructor and the new functionprintwhose name is identical
to that of a function in the flower class as an illustration of polymorphism:


rose::rose(string ftype, string rtype, string fcolor, float fprice)
{
type = ftype;
rosetype = rtype;
color = fcolor;
price = fprice;
}

void rose::print() const
{
cout << type <<" "<<rosetype<<" "<< color
<<" "<< "$"<<price << endl;
}

Now consider the main program:


int main()
{
flower A = flower();
A.print();

flower B = flower("annual", "red", 6.0);
string type=B.gettype();
string color=B.getcolor();
float price=B.getprice();
cout << type <<""<<color << " flower for $" << price << endl;
rose W = rose("perennial", "garden", "yellow", 9.39);
W.print();
return 0;
}
Free download pdf