The following code contains several header files in which classes are defined:
area, circle, ring, rectangle, pattern. area is the basis class, circle is a derivation. ring and rectangle are derivations of circle and pattern is a derivation of both circle and rectangle, describing a geometrical figure of a coloured circle, which contains a rectangle shaped hole. The class area defines a variable color which due to the double derivation will be contained in pattern twice. Anyways, I hope I can state this question in a way that you can follow along!
Consider this code:
int main() {
area *list[8];
ring blue_ring("BLUE",5,2);
pattern blue_pattern("BLUE",30,5,5);
list[0]=&blue_ring;
list[4]=static_cast<circle *>(&blue_pattern);
return 0;
}
What I don't understand is the cast in the third last line. The object blue_pattern is of the type pattern. Well and the pointer array list stores addresses pointing to objects of the type area. So why do I have to convert blue_pattern to an object of type circle.
This is an example from a programming beginners book. It says in there that the cast is necessary because the object pattern contains data from area twice. But I don't understand this reasoning.
Here's me trying to provide minimal code, which is just the headers:
"example0051.h"
#ifndef _AREA_
#define _AREA_
class area {
public:
area(char * n);
~area();
void getColor() const;
private:
char color[11];
};
#endif
"example0052.h"
#ifndef _CIRCLE_
#define _CIRCLE_
#include "example0051.h"
class circle : public area {
public:
circle(char * n, float a);
~circle();
float calculateArea() const;
private:
float radius;
};
#endif
"example0054.h"
#ifndef _RECTANGLE_
#define _RECTANGLE_
#include "example0051.h"
class rectangle : public area {
public:
rectangle(char * n, float a, float b);
~rectangle();
float calculateArea() const;
private:
float length;
float width;
};
#endif
"example0055.h"
#ifndef _PATTERN_
#define _PATTERN_
#include "example0052.h" // circle
#include "example0054.h" // rectangle
class pattern : public circle, public rectangle {
public: pattern(char * n, float a, float b, float c);
~pattern();
float calculateArea() const;
};
#endif