0

I am wondering are the following code the same:

//first
string str; int num;
stringstream(str)>>num;
//second
string str; int num;
(stringstream)str>>num;

I tried to run them and they work. Can you tell me that's the difference between them? Or they're the same? Thanks a lot!!!

whileone
  • 2,495
  • 3
  • 21
  • 30
  • 3
    Check here for a good explanation of the subject: http://stackoverflow.com/questions/32168/c-cast-syntax-styles – Hakan Serce May 28 '12 at 21:23

1 Answers1

4

As Luchian Grigore already told you they're equivalent.

The first one will use the stringstream::stringstream(const string&) constructor to create a temporary object. The second one is a C-style typecast, which is essentially the same as static_cast<stringstream>(str) >> num;. The static_cast<> will use the constructor above, so both are equivalent.

However, as Luchian already told you, you shouldn't use C-style typecasts. Use static_cast<> instead.

See also:

Community
  • 1
  • 1
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 1
    I thought I covered this: "The static_cast<> will use the constructor above, so both are equivalent". On the other hand, it's late and I could be missing something... – Zeta May 28 '12 at 21:38
  • No, it's late and I missed it. :) +1 for a better explanation. – Luchian Grigore May 28 '12 at 21:39
  • Why not just call the constructor directly? Are there any benefits to cast(either in c or c++ style)? I mean just for thiscase. @Luchian – whileone May 28 '12 at 21:42
  • 1
    @Gao the cast also calls the constructor. The only difference is in style. The two do exactly the same thing. – Luchian Grigore May 28 '12 at 21:47