Imagine I have such class hierarchy:
Base
A : Base
B : Base
C : B
I want to be able to retrive a string type from Base object (I need string, not enum). I want also to be able to compare object type to A type for example:
Object *object = new A();
if (object->type() == A::typename())
{
//hooray!
}
For now I’m planing to add a static function to each class:
static string typename() {return "Different name for each class";}
and then I will have to reimplement Base function virtual string type() for every derived class:
A: virtual string type() {return typename();} //A::typename
B: virtual string type() {return typename();} //B::typename
...
I think such design looks ugly. Is there some better way to achieve my goal?
Why I need this:
I’m developing a game. There is a tile map. Each tile has an array of objects on it. Some objects can be placed over the others. So i want to check if it is allow to put the object at the specific tile. For example: if tile has object with type “pot” then the flower can be put there.
You can achieve the same thing with
dynamic_cast. Your classes are polymorphic anyway.Note that this is at least a code smell. You shouldn’t need to find the actual type of classes in a well-thought design. What underlying problem are you trying to solve?
Also,
typenameis a keyword in C++, you should name your method differently.EDIT: A possible better solution for this would be to have a list of pairs of objects that can be stacked, and have virtual methods:
Now I see why you’d want the get name.