2

The following program compiles perfectly, even though the method "m", which is supposed to receive an instance of C, is called with an integer or a float.

class C {
public:
  const int value;
  C(int value) : value(value) {}
};

void m(C parameter) {
}

int main(void) {
  m(0);
  m(0.123);
  return 0;
}

If I call the method "m" with a string, I get this error message below. The error message indicates that the compiler is actually trying to build a class C from the string.

How is this possible? Is there a way to disable this behavior? How can I ensure that method "m" can only accept a parameter of class C?

Thank you !

J


test.cpp: In function ‘int main()’:
test.cpp:13:5: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
   13 |   m("");
      |     ^~
      |     |
      |     const char*
test.cpp:4:9: note:   initializing argument 1 of ‘C::C(int)’
    4 |   C(int value) : value(value) {}

Error message, saying method "m" accepts only instances of class C, not integers.

  • Make the converting constructor **explicit** if you don't want implicit conversion. – Jason Dec 10 '22 at 03:47
  • Also read: [What is a converting constructor in C++ ? What is it for?](https://stackoverflow.com/questions/15077466/what-is-a-converting-constructor-in-c-what-is-it-for) – Jason Dec 10 '22 at 03:47

2 Answers2

0

The reason is because single-argument constructors are taken to be casting operators in C++, so your declaration of C(int value) is telling the compiler that it's allowed to implicitly cast an int to a C by calling the constructor. To prevent this, you can use the explicit keyword, as in explicit C(int value).

0

It's because the compiler tries to find a constructor that it can use to convert the value into a class object implicitly. If they see it, then they will automatically convert it to the most appropriate instance. If you try to compile your program with -Wconversion, you will also get an error at m(0.123).

If you don't want this behavior, you must mark the constructor as explicit, preventing any implicit conversions.

Ayush Gupta
  • 1,166
  • 2
  • 9
  • 25