Re: Initializing C++ string inside a constructor
- From: Carlos Moreno <moreno_at_mochima_dot_com@xxxxxxxxxxxxxx>
- Date: Wed, 10 May 2006 23:43:45 -0400
jainarunk@xxxxxxxxx wrote:
Hello folks,
I want to initialize a variable type string s inside the class
constructor
My code looks like this
class Simple {
public:
Simple();
string s;
};
The problem I am encountering that I can not initialize s in an
initialization list, because my
value to initialize 's' is generated inside the constructor
Simple::Simple() {
// a string "somevalue" is generated here after some code
// can I do
s("somevalue");
or I will have to do
s= "somevalue";
The usual trick is having an auxiliary function that generates
the "somevalue":
Simple::Simple()
: s (get_s_value()) , ...
{}
However, depending on the situation, you might be better off
default-constructing it, then use reserve() to avoid reallocations,
and then use += to append the pieces.
If what you want is elegance and straightforward code, just stick
to the above solution (member initialization with auxiliary
functions; possibly private member functions -- or private static
member functions)
HTH,
Carlos
--
.
- References:
- Initializing C++ string inside a constructor
- From: jainarunk
- Initializing C++ string inside a constructor
- Prev by Date: Initializing C++ string inside a constructor
- Next by Date: mutli-thread's problem
- Previous by thread: Initializing C++ string inside a constructor
- Next by thread: Re: Initializing C++ string inside a constructor
- Index(es):
Relevant Pages
|