C++ Explicit Constructor – Importance of Using Explicit in C++ Constructors

c++explicit-constructor

Please refer to Wikipedia:Strategy Pattern (C++)

class Context
{
    private:
        StrategyInterface * strategy_;

    public:
        explicit Context(StrategyInterface *strategy):strategy_(strategy)
        {
        }

        void set_strategy(StrategyInterface *strategy)
        {
            strategy_ = strategy;
        }

        void execute() const
        {
            strategy_->execute();
        }
};

Why it is a good practice to use explicit for the constructor of Context?

Thank you

Best Answer

Because it's generally a good idea to use explicit unless you really want to allow implicit conversion. Since you're unlikely to use a Context object in a situation where you really gain anything from an implicit conversion, you're better off making it explicit.