Tuesday Coding Tip 20 — Be `explicit`!

4 10 57
calendar_todayschedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


If you choose to add a conversion operator for your class in C++, be sure to mark it as explicit or you can get nasty side-effects that will be hard to debug. For example, having an implicit conversion operator to bool will make the operator less-than “work” for your class, meaning that class can be used as a key for std::map and suddenly, all hell breaks loose.

#include <iostream>
#include <vector>

class A {
public:
    operator bool() {
        return true;
    }
};

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

int main() {
    // This is ok
    std::cout << (A() < A()) << std::endl;
    A a;
    if (a); // implicit conversion allowed

    // Error: error: invalid operands to binary expression
    std::cout << (B() < B()) << std::endl;
    B b;
    if (bool(b)); // explicit conversion required

    return 0;
}

Similarly, it is good practice to mark single parameter constructors explicit to prevent implicit conversions from trivial data types or to possibly track places where your object is copied.

class A {
public:
    A(int) {}
    A(const A&) {}
};

class B {
public:
    explicit B(int) {}
    explicit B(const B&) {}
};

int main() {
    A a1 = 10; // ok
    A a2 = { 10 }; // ok
    A a3 = a1; // ok

    B b1 = 10; // error: no viable conversion, explicit constructor is not a candidate
    B b2 = { 10 }; // error
    B b3 = B{10}; // ok
    B b4 = b1; // error
    B b5 = B{b1}; // ok

    return 0;
}
Part 8 of 20 in Tuesday Coding Tips
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31
chevron_left
1.5k Points71 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
25Posts
26Comments
12Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!