cybercop
cybercop

Reputation: 105

understanding the code

Can some one explain me this code there is a class StringStream . What i don't get is StringStream& write(char*). and if in cpp file there is

StringStream& StringStream::write(char* text)
{
   //what values can i return??
   //can i return address of character text is currently pointing to?
}

Upvotes: 1

Views: 98

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

This is a method that most likely modifies a StringStream instance, and returns a reference to a StringStream. So you should return a reference to the instance itself

StringStream& StringStream::write(char* text)
{
  // do stuff
  return *this;
}

This allows you to perform chaining:

StringStream s;
s.write("foo").write("bar");

That said, I would have expected the write method to take a const char*:

StringStream& write(const char* text);

since the method will presumably not modify the data passed to it, and is required in order to be able to correctly pass string literals such as the "foo" and "bar" in the example.

Upvotes: 3

deeiip
deeiip

Reputation: 3379

you can simply return a reference to stringStream class. As you are writing a member function of the same class you can simply return pointer to this. For more info about the StringStream class : click here

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

You'd return *this - i.e. a reference to the current object. (Well, you can return any non-local StringStream, but I guess the purpose is the one I stated)

This technique is usually used for method chaining - i.e. doing something like:

StringStream ss;
ss.write("Hello ").write("world!");

Upvotes: 4

Related Questions