2

Say I have a parent class Shape and two children class class Square and class Circle.

At some point in my code I do something like :

Shape* genericshape;
if(a_time_consuming_test()){
    genericshape = new Square;
} else {
    genericshape = new Cricle;
}

And later I would like to create another Circle or Square but I don't want to call a_time_consuming_test(). So can I use typeid or some equivalent to directly create the "right" shape ? Something like :

if(typeid(genericshape) == typeid(Square)){
    Square newsquare;
} else {
    Circle newcircle;
}

I guess that there should be a solution of that kind but this doesn't seem to be efficient because the day I have a third shape, like Triangle, I would need to check for each children of Shape. Would something like this be possible ?

Shape* newshape(&genericshape);

I mean, would newshape be a pointer on the same child class as genericshape?

EDIT

Looking at one of the answers, I should have specified that Shape, Square and Circle are actually template class.

3
  • I've too many solutions in my mind, but without knowing how exactly it is going to be used, I cannot say which solution would really be suitable for your case. You can try enum shape_type { circle, square, traingle, etc}; then save the type of your object in a variable of type shape_type, which you can later use. That is one way of doing it; other is, store a map of type_info and factory function, then use it. Apr 20, 2015 at 15:20
  • 3
    Sounds like you want a virtual constructor. Apr 20, 2015 at 15:20
  • 3
    I think you want a new object of the same type. Maybe have a virtual method Shape *Clone() or Shape *newShapeOfSameKind()in the base class which is overriden by derived classes so that it always creates an object of the proper type when called for a Shape * (which may point to a Square, Triangle or Circle). Apr 20, 2015 at 15:21

2 Answers 2

3

I believe that what you're looking for is a simple cloning functionality, with the slight twist that it will not clone the data, only the type. So you could add something like this to Shape:

struct Shape
{
  virtual std::unique_ptr<Shape> createEmptyObject() const = 0;

  // The rest as before
}:


struct Circle
{
  std::unique_ptr<Shape> createEmptyObject() const override
  { return std::make_unique<Circle>(/*ctor args here*/); }

  // The rest as before
};

And then use it like this:

Shape* genericshape;
if(a_time_consuming_test()){
    genericshape = new Square;
} else {
    genericshape = new Cricle;
}
// ...
auto anotherShape = genericshape->createEmptyObject();

Note: if you don't have access to C++14, you will have to replace make_unique with a manually constructed unique_ptr:

return std::unique_ptr<Shape>(new Circle(/*ctor args here*/));
7
  • This look nice, but would it be possible to use that solution with template class?
    – PinkFloyd
    Apr 20, 2015 at 15:30
  • @PinkFloyd Why not? It depends on how the template's parameters are used, of course. If you want a more accurate answer, provide a more accurate description in the question. Apr 20, 2015 at 15:30
  • If I'm not wrong, template and virtual are not really good friend... it is not possible to have a template virtual method ? or am I wrong ?
    – PinkFloyd
    Apr 20, 2015 at 15:32
  • @PinkFloyd You cannot have a virtual member function template, but a class template can have virtual member functions just fine. Apr 20, 2015 at 15:33
  • @PinkFloyd Added in C++11, very useful feature. You should read up on C++11, it has really improved the language. Apr 20, 2015 at 15:34
0

If you're ready to edit the following typelist, everytime you a add new shape:

using shapes = typelist<circle, rectangle>;

then I think the following solution should work (explained step-by-step):

shape* create(shape const * s)
{
    return create_impl(shapes(), s);
}

where create_impl and other supports are defined as:

template<typename T, typename ... Ts>
struct typelist{};

using shapes = typelist<circle, rectangle>;

template<typename T, typename ...Rest>
shape* create_impl(typelist<T, Rest...>, shape const *s)
{
     if ( typeid(T) == typeid(*s) )
        return new T();
     else
        return create_impl(typelist<Rest...>(), s);
}

template<typename T>
shape* create_impl(typelist<T>, shape const *s)
{ 
     return typeid(T) == typeid(*s)? new T() : nullptr;

}

Later if you add a new shape,say triangle, then just add it to the typelist:

using shapes = typelist<circle, rectangle, triangle>;

then everything should work again. No other code change.

And of course, you should use smart pointer instead of raw pointer, but I guess that is a small modification in the above code. The basic idea will remain same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.