Re: Initializing C++ string inside a constructor



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
--
.



Relevant Pages

  • Re: Inherited Methods and such
    ... what I see in Initialize is ... Now, what you want is to get in the constructor of some S derived from T, ... The base types and registry are part of the framework and the user ... provides the concrete factories. ...
    (comp.lang.ada)
  • Re: TypeInitializationException when calling a static function from a timer
    ... and is trying to deference a null reference. ... Set a break-point in the static constructor and step through. ... that TypeInitializationException means is that some kind of failure ... wait until the last moment to initialize types). ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Structs vs. Classes ?
    ... I say there is no reason to convert your structs to classes, ... Yes, you could initialize the values in a constructor, but that would also ... > the more elaborite data sets with operations (member functions) as ...
    (microsoft.public.vc.mfc)
  • Re: Initialization & Inheritance
    ... for a recent project I was trying to initialize members of a derived ... class from the constructor of the super class (done using an abstract ... initialize, but double initialization. ... if you used the pointer as it stood, ...
    (comp.lang.java.programmer)
  • Re: Initializing static readonly methods
    ... public class TestClass ... //So assigning a value to readonly is perfectly fine. ... //readonly values are has to be initialized in constructor. ... There is no other place to initialize them. ...
    (microsoft.public.dotnet.languages.csharp)