small detail

Hi there

I have question about small detail, is assigning value same as or part of initialization?

if we have following code:

1
2
3
4
5
string s1("Man"); // this is initialization 
string s2; // 

s2 = s1; // assigning 


so is string s2 uninitialized until s1 is assigned to s2?
should s2 be initialized to something (as I think this is current notion that
all variables should be initialized as soon as they are created?)

thanks :)

closed account (48T7M4Gy)
http://stackoverflow.com/questions/11556394/initializing-strings-as-null-vs-empty-string
std::string automatically initialises to "" (empty string), because it is a class - it's default constructor does it. So for this particular thing there is no need to worry about initialising it. But in general it is a very good idea to initialise things. With classes, one should ensure that each of the constructors fully initialise all it's members and base classes.

However with your code above you could do this:

std::string s2 = s1;

Edit:

There are lots of ways to initialise with C++, read about them here:

http://en.cppreference.com/w/cpp/language/initialization

Maybe you might choose one of those rather than assigning.
Last edited on
Hi both

thank you :)

@TheIdeasMan - I am going trough book and this was one of the examples. :)

Topic archived. No new replies allowed.