If you have:
#include <iostream>
#include <string>
class dog {
public:
dog(std::string name) : mname(name) {} // use initializer list
private:
std::string mname;
};
void Foo(dog g) {}
int main()
{
std::string name = "fido";
Foo(name);
}
Live Example
What this is doing is the comiler see's that you are calling Foo() but instead of giving it a dog we are giving it a string. So the compiler goes "Okay, Is there any way I can make a dog from a string? Lets look at the dog constructors. Oh look, I can construct a dog from a string. I will go ahead and make a dog from the string you passed to Foo() and everything will be okay."
This is what is called an implicit type cast. We can prevent this from happening by marking the constructor as explicit. Making a constructor explicit removes it from being used in implicit conversions
#include <iostream>
#include <string>
class dog {
public:
explicit dog(std::string name) : mname(name) {} // use initializer list
private:
std::string mname;
};
void Foo(dog g) {}
int main()
{
std::string name = "fido";
Foo(name);
}
Live Example
Now the compiler goes through the same steps but it can't use the constructor so you will get an compiler error. Now if we want the conversion we would manually have to do it like:
Foo(dog(name));