Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic_cast vs storing object type in a static enum?

I am developing a big hierarchy of classes for a framework that will require quite a lot of type casting when it gets done.

My question is, how stupid of an idea is to put in a static member that uses an enum to store all the object types in the hierarchy. Having the member static for every class will not increase the instanced object sizes, and will give a (potentially) faster way to determined the type of an object during runtime than dynamic_cast.

At least that's the basic idea. How adequate would this approach be, and are there any potential flaws?

like image 499
dtech Avatar asked Oct 22 '25 02:10

dtech


2 Answers

I don't know how you were gonna determine the type of each object from a static variable that is shared between the objects. Unless you have some virtual function that you override for each class, but then you don't need the static variable at all, just do something like this:

struct Base
{
   virtual int type() = 0;
};

struct Derived1 : public Base
{
   virtual int type() { return 1; }
};

struct Derived2 : public Base
{
   virtual int type() { return 2; }
};

Not the fastest solution, but several magnitudes faster than dynamic_cast or typeid.

like image 135
Timo Avatar answered Oct 24 '25 15:10

Timo


Here is a slightly better and different answer. I didn't wanted to change Timo's answer so submitted a new one. Rationale behind this is to avoid magic numbers. Sometimes typecasting and fiddling with objects is necessary to add new functionality when the aim is not to modify the original classes. But this should not allow someone to use magic numbers.

enum mytypeid {
    DERIVED1,
    DERIVED2,
};

struct Base
{
   virtual mytypeid type() = 0;
};

struct Derived1 : public Base
{
   static const mytypeid mytype = DERIVED1;

   virtual mytypeid type() { return mytype ; }
};

struct Derived2 : public Base
{
   static const mytypeid mytype = DERIVED2;

   virtual mytypeid type() { return mytype ; }
};

//...

void fn(Base &a) {
     if(a.type() == Derived1::mytype) {
        std::cout<<"1"<<std::endl;
     }
}
like image 28
Cem Kalyoncu Avatar answered Oct 24 '25 15:10

Cem Kalyoncu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!