Skip to content
Fix Code Error

What does the explicit keyword mean?

March 13, 2021 by Code Error
Posted By: Skizz

What does the explicit keyword mean in C++?

Solution

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:

int main ()
{
  DoBar (42);
}

The argument is not a Foo object, but an int. However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type.

The compiler is allowed to do this once for each parameter.

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42). It is now necessary to call for conversion explicitly with DoBar (Foo (42))

The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:

  • You have a MyString(int size) class with a constructor that constructs a string of the given size. You have a function print(const MyString&), and you call print(3) (when you actually intended to call print("3")). You expect it to print "3", but it prints an empty string of length 3 instead.
Answered By: Skizz

Related Articles

  • Vue.JS & Spring Boot - Redirect to homepage on 404
  • Callback functions in C++
  • Unit test Vuex getters that depend on other getters
  • What are access specifiers? Should I inherit with…
  • insert tables in dataframe with years from 2000 to…
  • How to filter a RecyclerView with a SearchView
  • Understanding implicit in Scala
  • Search match multiple values in single field in…
  • Azure CLI - az deployment group create -…
  • Specifying java version in maven - differences…
  • How to convert number to words in java
  • How to implement the factory method pattern in C++ correctly
  • how to make column bool data to be true with the…
  • What's wrong with overridable method calls in constructors?
  • Azure Availability Zone ARM Config
  • Javax.net.ssl.SSLHandshakeException:…
  • javax.el.PropertyNotFoundException: Property 'foo'…
  • Vue custom directive uses the updated Dom (or $el)
  • Why can't I define a default constructor for a…
  • How to inherit constructors?
  • What is a NullReferenceException, and how do I fix it?
  • Change column type in pandas
  • How can I make an Idempotent Callable Function with…
  • Is this request generated by EF Core buggy or is it my code?
  • Where and why do I have to put the "template" and…
  • LINQ query to include the parent name in the child item
  • Adding gif image in an ImageView in android
  • Get the name of an object's type
  • TypeError: 'list' object is not callable in python
  • Smart way to truncate long strings
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Accessing a nested polymer element
  • Why does C++ code for testing the Collatz conjecture…
  • Remix error The transaction has been reverted to the…
  • Nested class: Calling child class properties in parent class
  • How to create ranges and synonym constants in C#?
  • Creating a list of single type of objects
  • How to iterate through a JSON response with nested…
  • How to make Lodash orderBy to sort only the records…
  • Create the perfect JPA entity
  • Calculate the mean by group
  • Java 8: Lambda-Streams, Filter by Method with Exception
  • Confused about the Visitor Design Pattern
  • I want to create a SQLite database like in the…
  • How to pass a function as a parameter in Java?
  • What is an IndexOutOfRangeException /…
  • Item position in RecyclerView only changing when…
  • no match for ‘operator
  • JSON.net: how to deserialize without using the…
  • Are 'Arrow Functions' and 'Functions' equivalent /…
  • What does "Fatal error: Unexpectedly found nil while…
  • Angular 4 HttpClient Query Parameters
  • Specializing constructors with requires for a…
  • Builder pattern without inner class
  • "Undefined reference to" template class constructor
  • java-POST method 415 Error
  • Programmatically Lighten or Darken a hex color (or…
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • Is CSS Turing complete?
  • How can I manually compile a svelte component down…
  • Methods vs Constructors in Java
  • Default initialization of member variables or add…
  • Returning value from Thread
  • Can't resolve the implicit for a constrained class…
  • Convert Json String to C# Object List
  • Post request with many-to-many relation
  • How do I return the response from an asynchronous call?
  • TypeError: Cannot read property 'webpackJsonp' of undefined
  • When should static_cast, dynamic_cast, const_cast…
  • Add virtual network to existing Event hub namespace
  • Why after set mapping, index return nothing?
  • What does a "Cannot find symbol" or "Cannot resolve…
  • Pandas / Python - Compare numerically each row with…
  • When is assembly faster than C?
  • What does this symbol mean in JavaScript?
  • Map enum in JPA with fixed values?
  • Fastest way to iterate over all the chars in a String
  • What does "TypeError '✘✘✘' object is not callable" means?
  • How to fix Hibernate LazyInitializationException:…
  • Playing HTML5 video on fullscreen in android webview
  • How do I implement a callback in PHP?
  • Compiling ES6 and VUE JS not working in IE 11
  • What are type hints in Python 3.5?
  • How to apply rolling t.test with pandas?
  • Can I call a constructor from another constructor…
  • What does T&& (double ampersand) mean in C++11?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Reference — What does this symbol mean in PHP?
  • Undefined reference to 'vtable for ✘✘✘'
  • jQuery Mobile: document ready vs. page events
  • How can I create a Promise in TypeScript from a union type
  • What is The Rule of Three?
  • Automapper Aftermap alternative for Nested Mapping
  • Obtain most recent value for based on index in a…
  • So can't use weasyprint what is the best thing to do?
  • Draw in Canvas by finger, Android
  • C++ OpenGL stb_image.h errors
  • Getting value from appsettings.json in .net core
  • Auto-fit TextView for Android
  • How to place object files in separate subdirectory

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I invoke a Java method when given the method name as a string?

Next Post:

How can I add new array elements at the beginning of an array in Javascript?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error