explicit


Keyword: explicit

In C++, the explicit keyword is used to prevent implicit conversions or copy-initialization that the compiler might otherwise perform. It's primarily applied to constructors and conversion operators to make your code safer and more predictable.

Basic Usage of explicit with Constructors

When you declare a constructor as explicit, you are telling the compiler not to allow that constructor to be used for implicit conversions.

Example Without explicit:

When you declare a constructor as explicit, you are telling the compiler not to allow that constructor to be used for implicit conversions.

Example 1: Use without explicit:

#include <iostream>

class MyClass {
public:
    MyClass(int x) {
        std::cout << "Constructor called with " << x << std::endl;
    }
};

void printMyClass(const MyClass& obj) {
    std::cout << "In printMyClass function" << std::endl;
}

int main() {
    MyClass obj = 42;  // Implicit conversion from int to MyClass
    printMyClass(100);  // Implicit conversion and then passing to function

    return 0;
}

Explanation:

Example 2: with explicit:

#include <iostream>

class MyClass {
public:
    explicit MyClass(int x) {
        std::cout << "Constructor called with " << x << std::endl;
    }
};

void printMyClass(const MyClass& obj) {
    std::cout << "In printMyClass function" << std::endl;
}

int main() {
    // MyClass obj = 42;  // Error: Implicit conversion is not allowed
    MyClass obj(42);  // OK: Direct initialization is allowed
    // printMyClass(100);  // Error: Implicit conversion is not allowed
    printMyClass(MyClass(100));  // OK: Explicit conversion is required

    return 0;
}

Explanation:

Why Use explicit?

Example 3: Use with Conversion Operators

explicit can also be used with conversion operators to prevent implicit type conversions.

#include <iostream>

class MyClass {
public:
    explicit operator bool() const {
        return true;
    }
};

int main() {
    MyClass obj;
    // if (obj) {  // Error: Implicit conversion to bool is not allowed
    if (static_cast<bool>(obj)) {  // OK: Explicit conversion is required
        std::cout << "Object is true" << std::endl;
    }

    return 0;
}

Explanation

Summary

Using explicit is a good practice in cases where you want to avoid automatic type conversions that could lead to unexpected results or bugs in your code.

Previous Page | Course Schedule | Course Content