Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ implicit cast – How to force a warning

I am following a C++ training and I found out a behavior I find weird in C++ when learning about explicit keyword.

About the following snippet, it will compile and execute without any error or warning (compile with G++).

When calling Foo(5), it will automatically do an implicit conversion and actually call Foo(A(5)).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know I can forbid this behavior by making the constructor of A explicit : explicit A(int a); but my question is :

  • Is there a way to make G++ warn about implicit casts like that if I forgot to do so?

I tried g++ with -Wall -Wextra, I saw stuff on -Wconversion on SO but still build without any warnings.

Looking on the internet I found out some warnings seem to exist for C and ObjC, but not for C++…

enter image description here

Source: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

The snippet:

#include <iostream>

class A{
    public:
        A(int a) 
        {
            m_a = a;
        };

        int m_a;
};

void Foo(A a)
{
    std::cout << "Hello : " << a.m_a << std::endl;
}

int main(int argc, char** argv)
{
    Foo(5);  // No Warning ?
    
    return 0;
}

Output

Hello : 5

>Solution :

Is there a way to make G++ warn about implicit casts like that if I forgot to do so?

No, the fact that you have a choosen to have a non-explicit conversion constructor says that you want implicit conversion from int to Foo allowed.

If that is not desirable, then you always have the option of making this converting ctor explicit to forbid this completely. No way to have it both ways.


Now I realize that for code protection I should make all my CTORs explicit to avoid this, which I find a bit cumberstone

You pay for what you use.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading