


































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



































































int main() { derived x("Derived", "Base"); derived *ptr = &x; base bptr = (base) &x; cout << "Derived Class pointer points to..."; cout << ptr->show() << endl; cout << "Base Class pointer points to..." << bptr->show() << endl; return 0; } Output is: Derived Class pointer points to...Derived Base Class pointer points to...Base
c) To enable this kind of behavior: i) We declare draw in the base class shape as a virtual function: virtual void draw() const; ii) We redefine draw in each of the derived classes to draw the appropriate shape. iii) We declare a base-class pointer to point to the derived-class object. circle c; shape *shapePtr = &c;
// Member function definitions for class Point #include
// Definition of class Circle #ifndef CIRCLE1_H #define CIRCLE1_H #include "point1.h" class Circle : public Point { friend ostream &operator<<(ostream &, const Circle &); public: // default constructor Circle(double r = 0.0, int x = 0, int y = 0); void setRadius(double); double getRadius() const; virtual double area() const; virtual void printShapeName() const { cout << "Circle: "; } virtual void print() const; private: double radius; // radius of Circle }; #endif
// Definition of class Cylinder #ifndef CYLINDR1_H #define CYLINDR1_H #include "circle1.h" class Cylinder : public Circle { friend ostream &operator<<(ostream &, const Cylinder &); public: // default constructor Cylinder(double h = 0.0, double r = 0.0, int x = 0, int y = 0); void setHeight(double); virtual double area() const; virtual double volume() const; virtual void printShapeName() const { cout << "Cylinder: "; } virtual void print() const; private: double height; // height of Cylinder }; #endif
// Member and friend function definitions for class Cylinder #include
// Loop through arrayOfShapes and print the shape name, // area, and volume of each object to which the array points // using dynamic binding. cout << setiosflags(ios::showpoint) << setprecision(2); for (int i = 0; i < 3; i++) { arrayOfShapes[i]->printShapeName(); cout << endl; arrayOfShapes[i]->print(); cout << "\nArea = " << arrayOfShapes[i]->area() << "\nVolume = " << arrayOfShapes[i]->volume() << endl << endl; } return 0; } Output is: Point: [7, 11] Circle: [22, 8]; Radius = 3. Cylinder: [10.00, 10.00]; Radius = 3.3; Height = 10. Point: [7.00, 11.00] Area = 0. Volume = 0. Circle: [22.00, 8.00]; Radius=3. Area = 38. Volume = 0. Cylinder: [10.00, 10.00]; Radius=3.3; Height=10. Area = 275. Volume = 342.