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))
.
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 ...
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
CodePudding user response:
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.