Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Storing type of the object, what choice is better?

Tags:

c++

Without RTTI and with virtual functions.

I encountered 2 different common solutions to provide type of the object:

with virtual method call and keep id inside the method:

class Base {
 public:
 virtual ~Base();
 virtual int getType() const =0;
};
class Derived : public Base {
 public:
 virtual int getType() const { return DerivedID; }
};

with inline method call and keep id in the base class:

class Base {
 int id_;
 public:
 virtual ~Base();
 inline int getType() const { return id_; }
};

class Derived : public Base {
 public:
  Derived() { id_=DerivedID;}
};

What would be better choice in general and what is pro/cons of them?

like image 707
VladimirS Avatar asked Nov 11 '22 05:11

VladimirS


1 Answers

If you choose the second option with an ID in every derived class, you'll have an extra member in every object you create. If you use the first option of a virtual function, you'll have an extra pointer in the vtable which only exists once per class, not per object. If the class will have more than one virtual function, the first option is clearly better. Even if not, I think it more closely corresponds to what people will expect.

like image 140
Mark Ransom Avatar answered Nov 15 '22 06:11

Mark Ransom