3

Was reading this solution:

https://stackoverflow.com/a/42654357/8408220

(to the question "How to read integers till end of line?")

and I don't understand what this line is doing:

istringstream is( line );

I get that istringstream is a class, but what's the "is" part?

Is it doing this:

istringstream is = new istringstream(line);

?

edmqkk
  • 355
  • 2
  • 9
  • `is` is the name of the variable being declared. – Sid S Feb 17 '19 at 05:49
  • 1
    `is` is the same of the variable. It calls a constructor with `str` as the argument. Your last line is the equivalent in Java. – 0x499602D2 Feb 17 '19 at 05:54
  • I suppose I understood that. I just have never seen a variable taking an argument in a declaration/definition?—if that makes sense. – edmqkk Feb 17 '19 at 05:55
  • 1
    Well in Java you can do `String str = new String("hello")`. That's pretty much the same thing. – 0x499602D2 Feb 17 '19 at 06:08
  • @edmqkk "*I just have never seen a variable taking an argument in a declaration*" - then I suppose you havent been around C++ (or OOP in general) very long, have you? Constructing objects with input arguments is VERY common to do. Here's another example: `string Username("edmqkk");` Exact same concept. – Remy Lebeau Feb 17 '19 at 08:07
  • @RemyLebeau My first snarky comment! \ (•◡•) / _"...then I suppose you havent been around C++ (or OOP in general) very long, have you?"_ I feel like I'm finally a member of the SO community now. lol. I suppose I should have said, "I've never seen creating a new object without the new keyword." – edmqkk Feb 17 '19 at 16:46
  • @edmqkk welcome to C++. Many different ways to construct objects - automatic vs dynamic, manual vs RAII, etc. Have fun – Remy Lebeau Feb 17 '19 at 17:45
  • @RemyLebeau Thank you! It _is_ pretty different from Ruby and JavaScript Land. (>﹏ – edmqkk Feb 17 '19 at 17:51
  • 1
    @edmqkk [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/) – Remy Lebeau Feb 17 '19 at 18:34

1 Answers1

7
istringstream is( line );

is a definition of an automatically allocated istringstream named is initialized with the contents of line.

istringstream is = new istringstream(line);

will not compile. new dynamically allocates and constructs a new object and returns a pointer to it. You can only assign a pointer to a pointer. You could

istringstream * is = new istringstream(line);

and make is a pointer to an istringstream, but now you have to deal with managing the dynamic allocation. Make sure you

delete is;

when you no longer need it.

That said, prefer automatic allocation and give Why should C++ programmers minimize use of 'new'? a read before going the dynamic route.

user4581301
  • 29,019
  • 5
  • 26
  • 45