Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::string construct an object with the name as its constructor argument? [duplicate]

Tags:

c++

#include <string>          
#include <iostream>        

std::string(foo);          

int main()                 
{                          
    std::cout << foo.size() << "\n";                                                
    return 0;              
}                          

Results in 0, instead of an expected compile error for foo being undefined.

How is it able to do this? What is this called?

like image 749
jett Avatar asked Dec 17 '22 18:12

jett


1 Answers

std::string(foo);  //#1        

is the same as

std::string (foo); //#2         

is the same as

std::string foo; //#3          

The parentheses in #2 are redundant. They are needed in #1 as there is no whitespace separating std::string and foo.

like image 132
P.W Avatar answered Jan 12 '23 01:01

P.W