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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With