username_4567
username_4567

Reputation: 4903

Why this constructor is being called?

I'm confused about following program about why it calls first constructor.

class A  
{  
public:  
        A(const char *c="\0")  
        {  
                cout<<"Constructor without arg";  
        }  
        A(string c)  
        {  
                cout<<"New one";  
        }  

};  

int main()  
{  
        A a="AMD";  
        return 0;  
}  

Output is Constructor without arg

Upvotes: 2

Views: 136

Answers (3)

pmr
pmr

Reputation: 59811

Because a string literal is of type const char[] which implicitly converts to const char* which is preferred over the user-defined conversion std::string(const char*) (This is not really the signature of the string constructor, but enough for this explanation).

Also: initialization is not assignment. This is why a constructor and not operator= is called in the first place.

The preferred syntax for assignment in C++11 would be A a{"ASDF"};. It makes things more uniform.

Upvotes: 1

BSull
BSull

Reputation: 329

You're calling the constructor with a const char * because that is what "AMD" is. It's not a string. If you put A a(string("AMD")) it will work.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

"AMD" is a const char[], which is implicitly converted to const char*, so the first constructor [A(const char *c="\0")]is the best match.

Note that A(const char *c="\0") is not a constructor without an argument, it's a constructor which takes a single const char* as an argument, and has an optional default value to use when a const char* isn't specified. In this case, you're passing a const char*, so it uses it.

Upvotes: 8

Related Questions