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,016
  • 2
  • 17
  • 29
jett
  • 1,206
  • 2
  • 14
  • 33

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
  • 25,639
  • 6
  • 35
  • 72
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
  • 167,472
  • 9
  • 150
  • 334