Associating a string with a derived class I am using the following code to get a string that is associated with the class of an instance:

std::string gate = 
    dynamic_cast&lt;AND*&gt;(pComponent) != nullptr ? "AND" :
    dynamic_cast&lt;NAND*&gt;(pComponent) != nullptr ? "NAND" :
    dynamic_cast&lt;NOR*&gt;(pComponent) != nullptr ? "NOR" :
    dynamic_cast&lt;NOT*&gt;(pComponent) != nullptr ? "NOT" :
    dynamic_cast&lt;OR*&gt;(pComponent) != nullptr ? "OR" :
    dynamic_cast&lt;XNOR*&gt;(pComponent) != nullptr ? "XNOR" :
    dynamic_cast&lt;XOR*&gt;(pComponent) != nullptr ? "XOR" : ""
;


This works, but I feel like there should be a better way to do this. Perhaps create some kind of map with a reference to the class type of pComponent as key and the related string as value? 

All classes (AND, NAND, etc) inherit the same base class, Node. I have been thinking about adding the following code to Node:

virtual std::string get_gate() const = 0;


Then have every derived class implement the method, returning its string and call:

pComponent-&gt;get_gate();


Would this solution use memory for every class instance rather than once per class? For example I declare two objects of AND, would both of them allocate memory for the method? Will the compiler do something smart?
Would this solution use memory for every class instance rather than once per class?


Depends on whether your class already contains a vtable pointer or not.

If it does, there will be no additional memory requirements per instance (just another entry in the vtable, which is shared by all instances).

If it doesn't, each class will need an additional vtable pointer (that will be automatically inserted by the compiler to make virtual dispatch work). Also, a vtable will be generated, but those are one per class.

However, since you are already using (and that includes possibly deleting) instances of derived classes via pointer to base class, the base classes destructor (in this case Node::~Node()) should already be marked virtual so the derived classes destructor gets called correctly when deleting the Node*. This means each class should already have a vtable anyways - so no additional per-instance overhead.