0 votes
in C Plus Plus by
What does the explicit keyword mean?

1 Answer

0 votes
by

The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.

Here's an example class with a constructor that can be used for implicit conversions:

class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }

  int GetFoo () { return m_foo; }

private:
  int m_foo;
};

Here's a simple function that takes a Foo object:

void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}

and here's where the DoBar function is called:

<span style="border:0px; box-sizing:inherit; color:var(--highlight-keyword); font-family:inherit; font-stretch:inherit; font-style:inherit; font-variant:inherit; font-weight:inherit; line-height:inherit; margin:0px; padding:0px; vertical-align:baseline" class="hljs-key

Related questions

+1 vote
asked Jan 20, 2021 in C Plus Plus by SakshiSharma
0 votes
asked Jan 6, 2021 in C Plus Plus by GeorgeBell
...