Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Use of explicit keyword in C++
Next article icon

Use of explicit keyword in C++

Last Updated : 14 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Explicit Keyword in C++ is used to mark constructors to not implicitly convert types in C++. It is optional for constructors that take exactly one argument and work on constructors(with a single argument) since those are the only constructors that can be used in typecasting.

Let's understand explicit keyword through an example. 

Predict the output of the following C++ Program

CPP
// C++ program to illustrate default // constructor without 'explicit' // keyword #include <iostream> using namespace std;  class Complex { private:     double real;     double imag;  public:        // Parameterized constructor     Complex(double r = 0.0,              double i = 0.0) : real(r),                                imag(i)     {     }      // A method to compare two      // Complex numbers     bool operator == (Complex rhs)     {         return (real == rhs.real &&                  imag == rhs.imag);     } };  // Driver Code int main() {     // a Complex object     Complex com1(3.0, 0.0);      if (com1 == 3.0)         cout << "Same";     else         cout << "Not Same";     return 0; } 

Output
Same

As discussed in this article, in C++, if a class has a constructor which can be called with a single argument, then this constructor becomes a conversion constructor because such a constructor allows conversion of the single argument to the class being constructed. In this case, when com1 == 3.0 is called, 3.0 is implicitly converted to Complex type because the default constructor can be called with only 1 argument because both parameters are default arguments and we can choose not to provide them.
We can avoid such implicit conversions as these may lead to unexpected results. We can make the constructor explicit with the help of an explicit keyword. For example, if we try the following program that uses explicit keywords with a constructor, we get a compilation error.

CPP
// C++ program to illustrate  // default constructor with  // 'explicit' keyword #include <iostream> using namespace std;  class Complex { private:     double real;     double imag;  public:     // Default constructor     explicit Complex(double r = 0.0,                       double i = 0.0) :                       real(r), imag(i)     {     }      // A method to compare two      // Complex numbers     bool operator == (Complex rhs)     {         return (real == rhs.real &&                  imag == rhs.imag);     } };  // Driver Code int main() {     // a Complex object     Complex com1(3.0, 0.0);      if (com1 == 3.0)         cout << "Same";     else         cout << "Not Same";     return 0; } 

Output

Compiler Error : no match for 'operator==' in 'com1 == 3.0e+0'

We receive an error here because to avoid any unexpected errors we have made our constructor an explicit constructor and 3.0 won't be converted to Complex by our constructor on its own.

We can still typecast the double values to Complex, but now we have to explicitly typecast it. For example, the following program works fine.

CPP
// C++ program to illustrate  // default constructor with // 'explicit' keyword #include <iostream> using namespace std;  class Complex { private:     double real;     double imag;  public:        // Default constructor     explicit Complex(double r = 0.0,                       double i = 0.0):                       real(r) , imag(i)     {     }      // A method to compare two      // Complex numbers     bool operator == (Complex rhs)     {         return (real == rhs.real &&                  imag == rhs.imag);     } };  // Driver Code int main() {     // a Complex object     Complex com1(3.0, 0.0);      if (com1 == (Complex)3.0)         cout << "Same";     else         cout << "Not Same";     return 0; } 

Output
Same

Note: The explicit specifier can be used with a constant expression. However, if that constant expression evaluates to true, then only the function is explicit.


Next Article
Use of explicit keyword in C++

K

kartik
Improve
Article Tags :
  • C Language
  • C++
Practice Tags :
  • CPP

Similar Reads

    Const keyword in C++
    In this article, the various functions of the const keyword which is found in C++ are discussed. Whenever const keyword is attached with any method(), variable, pointer variable, and with the object of a class it prevents that specific object/method()/variable to modify its data items value.Constant
    10 min read
    Using Keyword in C++ STL
    The using keyword in C++ is a tool that allows developers to specify the use of a particular namespace. This is especially useful when working with large codebases or libraries where there may be many different namespaces in use. The using keyword can be used to specify the use of a single namespace
    6 min read
    C++ Keywords
    Keywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
    2 min read
    typeid operator in C++ with Examples
    typeid is an operator in C++. It is used where the dynamic type or runtime type information of an object is needed.It is included in the <typeinfo> library. Hence inorder to use typeid, this library should be included in the program.The typeid expression is an lvalue expression. Syntax: typeid
    3 min read
    C++: Methods of code shortening in competitive programming
    Shortcode is ideal in competitive programming because programs should be written as fast as possible. Because of this, competitive programmers often define shorter names for datatypes and other parts of the code. We here discuss the method of code shortening in C++ specifically.Type names Using the
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences