4
#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?

Arne Vogel
  • 6,346
  • 2
  • 18
  • 31
jett
  • 1,276
  • 2
  • 14
  • 34

2 Answers2

11
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.

P.W
  • 26,289
  • 6
  • 39
  • 76
0

The definition std::string(foo); calls the default constructor of std::string. The default constructor by definition is the one that can be called without arguments, and indeed you do not provide one.

A default-constructed string is empty, so its size is indeed 0.

MSalters
  • 173,980
  • 10
  • 155
  • 350