q0987
q0987

Reputation: 35982

C++ -- which constructor of string is call when we use string(0)?

Given the following code,

class A
{
public:
  A() : str(0) {}
private:
  string str;
};

Based on this http://www.cplusplus.com/reference/string/string/string/

string ( );
string ( const string& str );
string ( const string& str, size_t pos, size_t n = npos );
string ( const char * s, size_t n );
string ( const char * s );
string ( size_t n, char c );
template<class InputIterator> string (InputIterator begin, InputIterator end);

I don't see which constructor of string is called when we use the 'str(0)'.

Question> Can someone tell me which string constructor is used for 'str(0)'?

Upvotes: 2

Views: 802

Answers (2)

GManNickG
GManNickG

Reputation: 503983

This one:

string ( const char * s );

It's converted to a null pointer. (And also gives you undefined behavior, since s cannot be a null pointer.)

Upvotes: 7

sickgemini
sickgemini

Reputation: 551

It's using

string ( const char * s );

You're passing in a single argument and the argument isn't a const string reference so it has to be this version. The zero gets converted to a NULL pointer.

Upvotes: 4

Related Questions