prototype for toString() method

Q

qazmlp

I have a class containing 5-6 member data. I want to provide a toString() method
as a part of this class to help the users to do tracing.

const std::string& toString()
{
std::string objectData ;
objectData = "memberData1=" + memberData1 ;
objectData += " memberData2=" + memberData2 ;
objectData += " memberData3=" + memberData3 ;
objectData += " memberData4=" + memberData4 ;
objectData += " memberData5=" + memberData5 ;
return objectData ;
}

Is the function signature Ok? Or, do you suggest to make it as
"std::string toString()" ? If yes, why?
Do you suggest any improvements in the above code?
 
R

Rolf Magnus

qazmlp said:
I have a class containing 5-6 member data. I want to provide a
toString() method as a part of this class to help the users to do
tracing.

const std::string& toString()
{
std::string objectData ;
objectData = "memberData1=" + memberData1 ;
objectData += " memberData2=" + memberData2 ;
objectData += " memberData3=" + memberData3 ;
objectData += " memberData4=" + memberData4 ;
objectData += " memberData5=" + memberData5 ;
return objectData ;
}

Is the function signature Ok?
No.

Or, do you suggest to make it as "std::string toString()" ?
Yes.

If yes, why?

Beause otherwise, your program will probably crash. _Never_ return
references to local variables. They get destroyed before they can be
accessed by the caller.
Do you suggest any improvements in the above code?

If all those memberDataX variables are strings, it should be ok. If not,
you may want to use a stringstream.
 
P

Peter Koch Larsen

qazmlp said:
I have a class containing 5-6 member data. I want to provide a toString() method
as a part of this class to help the users to do tracing.

const std::string& toString()
{
std::string objectData ;
objectData = "memberData1=" + memberData1 ;
objectData += " memberData2=" + memberData2 ;
objectData += " memberData3=" + memberData3 ;
objectData += " memberData4=" + memberData4 ;
objectData += " memberData5=" + memberData5 ;
return objectData ;
}

Is the function signature Ok? Or, do you suggest to make it as
"std::string toString()" ? If yes, why?
Do you suggest any improvements in the above code?

This signature is not ok. You are returning a reference to a local variable.
On return from "toString" this variable does not exist anymore. Thus you
must return a std::string instead.
A still better solution would be to support streaming your data instead.
This is the normal way to provide conversion to string in C++ and would
enable you to use e.g. boost::lexical_cast when all you want is the string.

/Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top