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?
Asked
Active
Viewed 109 times
0

qu4lizz
- 317
- 2
- 12
-
Does this answer your question? [How do I check if an object's type is a particular subclass in C++?](https://stackoverflow.com/questions/307765/how-do-i-check-if-an-objects-type-is-a-particular-subclass-in-c) – Yevgeniy Kosmak Dec 19 '21 at 14:38
-
Having to get the actual types of objects when using polymorphism usually indicates a design flaw. – JensB Dec 19 '21 at 14:40
-
I'm aware that `dynamic_cast` should be used but I'm not sure how to pass argument of shape which I want to be filtered. – qu4lizz Dec 19 '21 at 14:40
1 Answers
1
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

Paul Sanders
- 24,133
- 4
- 26
- 48
-
-
1As `void foo (IShape::TypeOfShape t) { ... }`, for example. class enums are for the cool kids on the block because they don't pollute the global namespace. – Paul Sanders Dec 19 '21 at 15:22