User Defined Conversions

Explicit Keyword

How does the explicit keyword help prevent unintended conversions?

Abstract art representing computer programming

The explicit keyword in C++ is used to prevent unintended implicit conversions. It can be applied to constructors and typecast operators to ensure that they are not called implicitly.

This enhances the safety and clarity of your code by making conversions explicit. Let's look at an example using a constructor:

#include <iostream>

class Vector {
public:
  float x, y, z;

  // Explicit constructor
  explicit Vector(float value)
    : x(value), y(value), z(value) {}
};

void Move(Vector direction) {
  std::cout << "Moving in direction: "
    << direction.x << ", "
    << direction.y << ", "
    << direction.z;
}

int main() {
  // This is allowed as we're explicitly
  // constructing a Vector
  Vector v1(1.0f);  

  // This is also explicit, so is allowed
  Move(Vector(1.0f));  

  // This woul require an implicit conversion
  // so it is not allowed
  Move(1.0f); 
}
error: 'void Move(Vector)': cannot convert argument 1 from 'float' to 'Vector'
note: Constructor for class 'Vector' is declared 'explicit'

In this example, the Vector constructor is marked as explicit, meaning you cannot pass a float directly to functions expecting a Vector without an explicit cast.

This prevents mistakes where a float might be mistakenly passed to a function expecting a Vector. Similarly, you can use explicit with typecast operators:

class MyType {
 public:
  // Explicit typecast operator
  explicit operator int() const { return 42; }
};

int main() {
  MyType obj;

  // Explicit conversion allowed
  int A = static_cast<int>(obj); 

  // Error: implicit conversion not allowed
  int B = obj;  
}
error: 'initializing': cannot convert from 'MyType' to 'int'
note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Here, the explicit typecast operator prevents implicit conversion to int. You must use static_cast<int>(obj) to perform the conversion explicitly.

By using explicit, you can make your code more robust and easier to understand, as it avoids unintended conversions that could lead to subtle bugs.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved