0

Would appreciate clarification on what exactly is happening when a constructor has only one argument and it is said that it does an implicit cast to the class type - right there It is confusing to me because :

class dog {
public :
        dog(string name) {    mname = name;}
private :
         string mname;
};

I don't understand how a type string can be converted to a type dog, I can see how it can be passed in and SET another string but if a string is converted to type dog what would that even mean? Would it be type dog that gets assigned a bit wise copy of a string?

2
  • Possibly you are looking for this :: stackoverflow.com/questions/12340257/… Commented Jul 28, 2015 at 3:22
  • Note that the title of the question I linked to doesn't match up, but the accepted answer covers implicit typecasting perfectly. (Like NathanOliver's answer, really.) Commented Jul 28, 2015 at 12:32

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.