multiple inheritance question - c++ |
||
![]() ![]() Gamma Cpt thinkt4nk I'm trying to brush up on my OOP skills in c++, and I can't seem to figure out how I can pass a derived class' member data back to the base class. This bit of code shows my example where the Rectangle class is derived from Shape and Drawable. The Square class is derived from the Rectangle class directly. I want to create a square or rectangle object and call the draw method on that object. The only problem is that I can't get Drawable to recognize the member data in the object. Is there a problem with my casting? #include <iostream>
class Shape
{
public:
Shape();
Shape(int);
virtual ~Shape(){}
int getItsArea() const {return *itsArea;}
private:
int *itsArea;
};
class Drawable
{
public:
Drawable();
virtual ~Drawable(){}
void draw();
};
class Circle : public Shape
{
public:
Circle();
Circle(int);
virtual ~Circle(){}
int getItsRadius() const {return *itsRadius;}
private:
int *itsRadius;
};
class Rectangle : virtual public Shape, virtual public Drawable
{
public:
Rectangle();
Rectangle(int);
Rectangle(int, int);
virtual ~Rectangle(){}
int getItsLength() const {return *itsLength;}
int getItsWidth() const {return *itsWidth;}
protected:
int *itsLength;
int *itsWidth;
};
class Square : public Rectangle
{
public:
Square();
Square(int);
~Square(){}
};
//constructors
Shape::Shape()
{
itsArea = new int(0);
}
Shape::Shape(int area)
{
itsArea = new int(area);
}
Drawable::Drawable()
{}
Circle::Circle():
Shape(0)
{
itsRadius = new int(0);
}
Circle::Circle(int radius):
Shape(3.14*(radius * radius))
{
itsRadius = new int(radius);
}
Rectangle::Rectangle():
Shape(0)
{
itsLength = new int(0);
itsWidth = new int(0);
}
Rectangle::Rectangle(int square):
Shape(square * square)
{
itsLength = new int(square);
itsWidth = new int(square);
}
Rectangle::Rectangle(int length, int width):
Shape(length * width)
{
itsLength = new int(length);
itsWidth = new int(width);
}
Square::Square():
Rectangle(0)
{}
Square::Square(int square):
Rectangle(square)
{}
//draw function
void Drawable::draw()
{
for(int i=0;i<*itsLength;i++)
{
cout << endl;
for(int j=0;j<*itsWidth;j++)
{
cout << "x";
}
}
cout << endl;
}
int main()
{
Square *mySquare = new Square(4);
mySquare->draw();
return 0;
}
.i1i1 thinkt4nk 1i1i.
s/zig//g;
Replies:
|
||
| CyberArmy::Forum v0.6 Generated In 0.02260 seconds |