I want to create a class with a function that adds elements to a list that contains subclasses of an abstract superclass.
I have an abstract class "Shape" with multiple subclasses. In my example, I use the subclass "Circle" but there may be "Rectangle", "Polygon" or any other shape.
The ShapeList class looks (simplified) like this:
ShapeList.h file
#include "Shape.h"
class Node;
class ShapeList
{
public:
ShapeList() : first(0){};
void add( const Shape& s );
private:
Node *first;
};
ShapeList.cpp file
#include "ShapeList.h"
class Node
{
public:
friend ShapeList;
Shape *shapes;
Node *next;
Node( Node *n, Shape *s) : next(n), shapes(s){};
};
void ShapeList::add( const Shape& s ){
first = new Node(first, s);
}
Super Class Shape (also simplified)
class Shape
{
public:
Shape();
Shape(double x, double y) : posX(x), posY(y){};
protected:
virtual const double area() = 0;
double posX;
double posY;
};
Subclass Circle which is one of several subclasses
Circle.h file
#include <math.h>
#include <Shape.h>
class Circle : public Shape
{
public:
Circle();
Circle( double x, double y, double r) : Shape(x, y), radie(r){};
const double area();
private:
double radie;
};
Circle.cpp file
#include "Circle.h"
Circle::Circle()
: Shape(0, 0), radie(0)
{}
const double Circle::area(){
return radie * radie * M_PI;
}
Then I want to do, for example, somthing like this:
#include <iostream>
using namespace std;
#include "shapelist.h"
#include "Circle.h"
int main()
{
ShapeList list;
list.add( Circle( 5,5, 3) );
}
So the questions are:
How can I pass a subclass as an argument to a function with a superclass parameter? Is it possible? Create add functions for each shape and Template is not an option.
I have tested and changed a lot in add function but I do not get it working. What's wrong?
Just one note is that I have made changes so many times in the code that I may have destroyed something obvious in the code posted here. Can you point out the mistake?