Search code examples
c++debuggingvirtual

C++ - Best way to create a virtual function to print debug messages


Possible Duplicate:
pure virtual function and abstract class

I have a class and I want to create a virtual function that will be used to print debug information. Any class that inherits this class will have to implement this virtual function. This way different classes could print the debug messages to different output devices such as std::cout, labels, files etc.

The base class won't be aware of the messages destination. But I don't know the best way to do this. I'm thinking of using something like printf() which can print an arbitrary number of parameters. But I don't know what that would be accomplished. Any ideas?


Solution

  • I would do something like this:

    class Base 
    { 
    protected:
       virtual int doDebug(const std::string& Msg) const = 0; 
    
    public:
       int Debug(const char* MsgFmt, ...) const; 
    }; 
    
    int Base::Debug(const char* MsgFmt, ...) const
    {
        std::string sMsg;
        va_list args;
    
        va_start(args, MsgFmt);
        int len = vsnprintf(NULL, 0, MsgFmt, args);
        if (len > 0)
        {
            sMsg.resize(len);
            vsnprintf(&sMsg[0], len + 1, MsgFmt, args);
        }
        va_end(args);
    
        return doDebug(sMsg); 
    }
    

    That way, you still provide the caller with flexible formatting, but the derived classes do not have to worry about that because they are given only pre-formatted text.