Reputation: 1031
I have a C++ application which has the following classes:
class AAA
class BBB
inherits from AAA
class CCC
inherits from AAA
class DDD
inherits from CCC
(All of the classes are marked as public
)
Now I have the following map:
map <DWORD, AAA*>
I find an AAA
object in the map
, by a DWORD id
, but now I want to know what is the type of AAA
:
this will be the logic:
if(AAA is BBB)
{
...
}
if(AAA is CCC)
{
...
}
if(AAA is DDD)
{
...
}
Do you know how to write it in C++ (without adding a polymorphic function of getType()
)?
Upvotes: 3
Views: 2794
Reputation: 36896
Requiring this indicates you are doing it the wrong way. You are trying to replicate something that virtual methods were invented for. Just put a virtual method in your base class.
class AAA
{
public:
virtual void DoSomething() = 0;
}
class BBB : public AAA
{
public:
void DoSomething() { ... }
}
class CCC : public AAA
{
public:
void DoSomething() { ... }
}
class DDD : public AAA
{
public:
void DoSomething() { ... }
}
And in your calling code, your logic is simple:
// no need for if() blocks. it's the point of virtual methods.
AAA* somePointer;
...
somePointer->DoSomething();
I realize you maybe can't just copy / paste your current "dosomething" code into this. But this is the pattern you should be using for this scenario. Perhaps instead of DoSomething
it makes more sense to have something like GetSomeInfo
, that the caller can use to do whatever it needs to do. The specific usage of this pattern depends on your context.
Upvotes: 7
Reputation: 7687
If your object is polymorphic (i.e. has at least one virtual function), do a dynamic_cast<T*>
.
if the result is not NULL
then you have an object of type T
. But a virtual function would be a better way to go IMO.
Note: RTTI will need to be enabled on your compiler (which it will be in the vast majority of situations)
EDIT: Thanks to @Als and @flipchart for additions
Upvotes: 4