Introducing my issue with some comments. Each comment refers to the code below:
comment1: myShapeVector stores Shape*
comment2: Adding up the vector either with with circle or rectangle objects
comment3: The returnPtr() member function is intended to be used for returning either a Circle* or an Rectangle* depending on which id is passed, it is intended to used as a tool to convert the myShapeVector[i] element (which is an object*) to an circle* or rectangle *. I thought using a template class is necessary because only those can return different pointers
comment4: Additionally id is used to refer to a certain element of the vector
comment5: Converting an ShapePtr* to Circle* by static_cast conversion works fine
comment6: This line returns an error. Somehow the returnPtr() does not return the expected Circle*. From my point of view a template class is feasible of returning different pointers*. The T returnPtr(int id) looks fine to me.
#include <iostream>
#include <vector>
class Shape {};
class Circle : public Shape {};
class Rectangle : public Shape {};
template <class T, class d, class c> class ShapeVector {
public:
T returnPtr(int id) { //comment 3
if (id == 0) {
return (static_cast<Circle *>(myShapeVector[0])); //comment 4
} else if (id == 1) {
return (static_cast<Rectangle *>(myShapeVector[1]));
} else {
return nullptr;
}
}
std::vector<Shape *> myShapeVector; // comment 1
};
int main() {
ShapeVector<Shape *, Rectangle *, Circle *> myShapes;
myShapes.myShapeVector.push_back(new Circle); //comment 2
myShapes.myShapeVector.push_back(new Rectangle);
Circle *b = myShapes.returnPtr(0); //comment 6 / please see errors below
Circle *c = static_cast<Circle *>(myShapes.myShapeVector[0]); //comment 5
return 0;
}
a value of type "Shape *" cannot be used to initialize an entity of type "Circle *" C/C++(144)
invalid conversion from ‘Shape*’ to ‘Circle*’ [-fpermissive] gcc failure message
For sure the code lacks of knowledge using templates.
- At first stage my main concern is about how to return child class* from an vector which which contains parent class*?
- Is it correct that a template class is needed for this procedure?