The explicit keyword

Assume we have a class that’s doing all kinds of interesting stuff. Its public members could be, e.g.:

class Convertor
{
public:
  Convertor();
  Convertor(char const *str);
  Convertor(Convertor const &other);
  ~Convertor();
  operator char const*();
  void anyOtherMemberFunction();
};

Objects of the class Convertor may be constructed using a default constructor and using a char const *. Functions
might return Convertor objects and functions might expect Convertor objects as arguments. E.g.,

Convertor returnConvertorObject()
{
  Convertor convertor;
  return (convertor);
}
void expectConvertorObject(Convertor const &object)
{
...
}

In cases like these, implicit conversions to Convertor objects will be performed if there are constructors having one
parameter (or multiple parameters, using default argument values), if an argument of the type of the single parameter
is passed to or returned from the function. E.g., the following function expects a char const * and returns an Convertor
object due to the implicit conversion from char const * to Convertor using the Convertor(char const *) constructor as
middleman:

Convertor returnConvertorObject(char const *str)
{
  return (str);
}

This conversion will generally occur wherever possible, and appears to be something like a `reversed’ conversion
operator: in applicable situation the constructor expecting one argument will be used if the argument is specified, and
the class object is required.
If such implicit use of a constructor is not appropriate, it can be prevented by using the explicit modifier with the
constructor. Constructors for which the explicit modiefier are used can only be used for the explcit definition of
objects, and cannot be used as implicit type convertors anymore. For example, to prevent the implicit conversion from
char const * to Convertor the class interface of the class Convertor must contain the constructor

explicit Convertor(char const *str);
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Add to favorites
  • LinkedIn
  • Propeller
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

Related posts:

  1. where to place inline keyword, in definition or declaration?
  2. Implicit Type Conversions – part 2
  3. Constructors: Copy Constructors, What, Why, How, When …
  4. C++ Basics Tutorial – Lesson 8
  5. Overloading operator new(size_t)

Leave a Reply