- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What does the explicit keyword mean in C++?
The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo −
class Foo { public: Foo(int n); // allocates n bytes to the Foo object Foo(const char *p); // initialize object with char *p };
Now if you try
Foo mystring = 'x';
The char 'x' is implicitly converted to int and then will call the Foo(int) constructor. But this is not what was intended. So to prevent such conditions and make the code less error-prone, define the constructor as explicit −
Example
class Foo { public: explicit Foo (int n); //allocate n bytes Foo(const char *p); // initialize with string p };
Advertisements