It was hard to make the headline very clear about the subject, but I will try to explain the context (and there are some of the code below). Note. I saw answers to similar questions, but they only considered cases with 1 child class. Therefore, they did not help me, because I have 2 child classes.
Context:
I have a parent Shape class that has 2 children: a circle and a square. I will have a vector of Shape objects, but these Shape objects will actually only be Circle or Square objects. I need the Circle and Square classes in order to have the same parent class so that I can store them as in the same vector.
The trick is that I will need to use Shape objects in the vector to call methods implemented in either the Circle class or the Square class, so I need to have a βvirtualβ version of these methods in the parent class of the Form.
Here is the simplified piece of code for my classes:
Shape.h:
class Shape{
public:
std::string getColor();
virtual int getRadius() = 0;
virtual int getHeight() = 0;
virtual int getWidth() = 0;
protected:
std::string color;
};
class Circle : public Shape{
public:
int getRadius();
private:
int radius;
};
class Square : public Shape{
public:
int getHeight();
int getWidth();
private:
int height;
int width;
};
In Shape.cpp, I have something like this:
std::string Shape::getColor(){
return color;
}
int Circle::getRadius(){
return radius;
}
int Square::getHeight(){
return height;
}
int Square::getWidth(){
return width;
}
errors occur in main.cpp when I want to create Circle and Square objects:
Circle *c = new Circle(...);//Error: cannot instantiate abstract class
//pure virtual function "Shape::getHeight" has no overrider
//pure virtual function "Shape::getWidth" has no overrider
Square *s = new Square(...);//Error: cannot instantiate abstract class
//pure virtual function "Shape::getRadius" has no overrider
It seems to me that I will need the declaration of "getRadius" in the Square class and the declaration of "getHeight" and "getWidth" in the Circle class ...
I tried adding them using a virtual one, but this does the abstract Circle and Square classes, so I cannot create any objects with them.
Is there any way to make this work?
, stackoverflow. , . !