The following code throws compilation error:
#include <stdio.h>
class Option
{
Option() { printf("Option()\n"); };
public:
explicit Option(const Option& other)
{
printf("Option(const)\n");
*this = other;
}
explicit Option(Option& other)
{
printf("Option(non-const)\n");
*this = other;
}
explicit Option(const int&)
{
printf("Option(value)\n");
}
};
void foo(Option someval) {};
int main()
{
int val = 1;
Option x(val);
foo(x);
}
The error thrown is:
main.cpp:31:10: error: no matching function for call to ‘Option::Option(Option&)’
foo(x);
^
main.cpp:5:5: note: candidate: ‘Option::Option()’
Option() { printf("Option()\n"); };
^~~~~~
main.cpp:5:5: note: candidate expects 0 arguments, 1 provided
main.cpp:25:6: note: initializing argument 1 of ‘void foo(Option)’
void foo(Option someval)
The error goes away if I remove the explicit keyword from explicit Option(const Option& other)
Can someone explain to me what is the cause of compilation error?
Also, if there a difference between explicit Option(const Option& other)
and explicit Option(Option& other)
?