Get name of a class programmatically at run-time

 

Hi all -- is there a straightforward way to find out the name of a class during run-time? I hoped MQL would have some predefined macro akin to __FILE__ or __FUNCTION__ but, alas, there is no __CLASS__...

Predefined Macro Substitutions - Named Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5

As a workaround I tried this, however unless I redefine the method in classes derived from MySampleBaseClass it will always return the base class name.

string MySampleBaseClass::GetClassName()
{
   string str_array[];
   if (StringSplit(__FUNCTION__, ':', str_array) > 0)
      return str_array[0];
   else
      return "";
}

Another workaround on top of that would be to create a macro with the code above instead, but I'm thinking to myself -- is there an easier way?

Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
  • www.mql5.com
Predefined Macro Substitutions - Named Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
class Base : public CObject
{
public:
        const string    m_class_name;
private:
        Base(string class_name):m_class_name(class_name){;}
}

class Derived : public Base
{
public: 
        Derived():Base("Derived"){;}
}

Try something like that.

 
  1. You know the name when you compile; no need for run time code.
  2. class Base : public CObject
    {
    public:
            virtual string class_name{return "Base";}
    }
    
    class Derived : public Base
    {
    public: 
            virtual string class_name{return "Derived";}
    }

 

Thank you both, that will work for me... sometimes its so obvious and staring you in the face that you can't see it :-)

Anyway, I guess (being lazy as I am) I was looking for a "set-and-forget solution" that I didn't need to worry about in derived classes.

 

Is there no such thing like

__func__


in c++?

 
Dmitri Diall: -- is there a straightforward way to find out the name of a class during run-time? 
class Cclass{
 public:
   void iAM(){ Print(typename(this));} // "Cclass"
};
Reason: