Im trying to put a Point a Circle and a Cylinder (3 different classes deriving from each other, point deriving from Shape)inside a base class Shape array.
But im having trouble doing this correctly. Was wondering if anyone had some ideas.
I need to assign a value of type cylinder, circle, point to that of type shape.
What trouble exactly? Compile errors - then post them here.
If that is the case, then also provide the code which the compile errors refer to, and make it clear which lines of your code match the compiler errors. You can put a firstline=x in the opening code tag to start the line numbers at line x.
Your description of the inheritance isn't clear.
Sorry, I don't mean to sound short, but it's 03:30AM here - I might well go to bed soon. If you provide enough info there are plenty of others with much more knowledge than me to help :)
My base class is shape. Point derives from shape. Circle derives from point. Cylinder derives from circle.
My error says i cant assign a value of type point to that of type shape.
my red squiggly is under the assignment operator in the code shown above.
in order to fix this myself i tried creating a function with static cast to try and convert it, ive seen my professor do it before. but it turned out to be a complete disaster so i decided not to use that idea at all and im lookin for help
class A { };
class B : public A { };
class C : public B { };
int main()
{
A* baseArray[3];
baseArray[0] = new A;
baseArray[1] = new B;
baseArray[2] = new C;
// delete stuff
return 0;
}
My base class is shape. Point derives from shape. Circle derives from point. Cylinder derives from circle.
Now that I am wide awake, it seems to me your design should change a bit - prefer composition over inheritance - these classes should be in their own header files:
1 2 3
class CShape {
//virtual functions
};
class CPoint : public CShape {};
1 2 3 4 5 6 7 8 9
#include CPoint.h
class CCircle : public CShape {
private:
CPoint CentrePoint;
double Radius;
public:
// get & set functions
};
1 2 3 4 5 6 7 8 9 10
#include CCircle.h
class CCylinder : public CShape {
private:
CCircle CylBaseSurf ;
double CylHeight;
public:
// get & set functions
};
This code seems a bit different in that you have to create points & circles in order to create a cylinder, but you can do this in the constructor, or even better call the other constructors in the initialiser list.
Polymorphism as per IceThatJaw's example should still work. Remember that a pointer to a derived class is a valid pointer to a base class.