5

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

4
  • If this isn't a good place to use explicit, then what is? Commented Nov 8, 2010 at 5:23
  • 4
    @Potatoswatter: Anywhere you have a class whose name can't be said aloud in polite company. Commented Nov 8, 2010 at 5:41
  • the above remark from James is not to be taken seriously; just for the naive beginner Commented Nov 8, 2010 at 6:20
  • To Potatoswatter, just define the constructor without using explicit. -- thank you Commented Nov 9, 2010 at 4:37

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

7

Well, explicit constructors are always safe, but can be inconvenient. explicit ensures a compilation error should you provide a StrategyInterface* where a Context is expected. In doing so, it prevents construction of a temporary Context. This becomes particularly important in certain circumstances, e.g.:

  • Context takes ownership of the pointed-to StrategyInterface, and deletes it in the destructor
  • Context construction/destruction performs other expensive or inappropriate actions
  • it disambiguates some operations implicitly, and makes others ambiguous, where it might be more appropriate to have the programmer consider how to resolve the ambiguity (e.g. should an attempt to compare a Context and a StrategyInterface* produce a compile-time error, result in comparing StrategyInterface*s, StrategyInterfaces or Contexts?)

If a Context is practically a drop-in-replacement for a StrategyInterface, just with some minor logging or other enhancements, then it may be appropriate to allow implicit construction, much as std::string can be constructed from const char*. When they're clearly independent things, or when the lifetime of a Context should exist beyond any given usage of a StrategyInterface, then an explicit constructor's indicated.

(Note: these guidelines are pretty rough - more a starting point than an end - comments welcome)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.