Search code examples
c++staticinitializerstatic-constructor

Initialize static class member with an instance of a derived class if type is a reference to a pure virtual base class


When I try to initialize a static member in my Action.cpp file via

ILogger & Action::m_activeLogger = DefaultLogger();

the compiler (C++11 + Linux) says:

cannot bind non-const lvalue reference of type "ILogger &" to an rvalue of type ILogger

How can I initialize my static member variable pointing to the instance?

Minimal example:

I have an interface base class (pure virtual)

base.h:

class ILogger {
public:
    virtual ~ILogger();
    virtual void write(std::string msg);
}

with DefaultLogger.h as an derived class as implementation (CPP file not shown here):

class DefaultLogger : public ILogger {
public:
    ~DefaultLogger();
    void write(std::string msg);
}

In Action.h I am using a static member variable with a reference to the base class:

class Action {
    static ILogger & m_activeLogger;
    // getter/setter to register another logger...
}

How can I initialize the static member variable m_activeLogger with my derived class?


Solution

  • Store your logger not by reference, but with a unique_ptr and dereference it for the accessor:

    class Action {
        static std::unique_ptr<ILogger> m_activeLogger;
        // getter/setter to register another logger...
    }
    

    And then should have an accessor to get it:

    ILogger& get_instance(){return * m_activeLogger;}
    

    Otherwise, you won't be able to set another logger! At least not with a reference.

    Side note, the virtual call should probably take a const& to the string, and then tag them with override:

    void write(const std::string& msg) override;