I have class Set
which consists of dynamically allocated IShape
where IShape
is inherited by Square, Rectangle etc. and I need to make filter function to create new set of only certain type (E.g. Squares). Basically to go through existing set and pick only shape which is defined somehow (through parameters?) and create new set of that shape. How could this be done?
CodePudding user response:
To avoid using dynamic_cast
, have your IShape
class declare a pure virtual function called (say) GetTypeOfShape
. Then override that in each of your derived classes to return the type of shape that each represents (as an enum
, say). Then you can test that in your filter function and proceed accordingly.
Example code:
#include <iostream>
class IShape
{
public:
enum class TypeOfShape { Square, Rectangle /* ... */ };
public:
virtual TypeOfShape GetTypeOfShape () = 0;
};
class Square : public IShape
{
public:
TypeOfShape GetTypeOfShape () override { return TypeOfShape::Square; }
};
class Rectangle : public IShape
{
public:
TypeOfShape GetTypeOfShape () override { return TypeOfShape::Rectangle; }
};
// ...
int main ()
{
Square s;
Rectangle r;
std::cout << "Type of s is: " << (int) s.GetTypeOfShape () << "\n";
std::cout << "Type of r is: " << (int) r.GetTypeOfShape () << "\n";
}
Output:
Type of s is: 0
Type of r is: 1