It was hard to make the title very clear about the subject, but I will try to explain the context (and there is some of the code down below). Note: I have seen similar questions answered, but they only treated the cases with 1 child class. So they didn't really help in my case, because I have 2 child classes.
Context: I have a parent class Shape that has 2 child: Circle and Square. I will have a vector of Shape objects, but these Shape objects will actually only be either Circle objects or Square objects. I need the Circle and Square classes to have the same parent class so that I can store them both in the same vector.
The trick is that I will need to use the Shape objects in the vector to call methods implemented in either the Circle class or the Square class, therefore, I need to have a "virtual" version of those methods in the parent class Shape.
Here is a simplified part of the code for my classes:
Shape.h :
class Shape{
public:
std::string getColor();
virtual int getRadius() = 0; //Method implemented in Circle
virtual int getHeight() = 0; //Method implemented in Square
virtual int getWidth() = 0; //Method implemented in Square
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;
}
The errors occurs in the 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
So it seems like I would need a declaration of "getRadius" in the Square class and a declaration of "getHeight" and "getWidth" in the Circle class...
I tried adding them with virtual, but that makes Circle and Square abstract classes, so I can't create any objects with them.
Is there a way to make this work?
This is my first question posted on stackoverflow. I hope everything is clear. Thanks for the help!
Shape
in each of the derived classes or those classes become abstract base classes and cannot be instantiated. – larrylampcoShape
notShapes
. – larrylampco