Reputation: 610
Now from my knowledge what I know is that you should always set your integers to a specific value because they will be assigned garbage values by the compiler. Now I was using a program and initialized an array of strings and was wondering is it the same case with std::strings. Are they assigned some garbage value too? What about other primitive types? And is this with only primitive types like int, long, char. Also if you have an object with a std::string, int etc member variables; are they assigned garbage values too? (I'm working on C++).
Plus is it the same with other programming languages?
Upvotes: 2
Views: 320
Reputation: 36597
All "primitive types" (int, double, float, pointers (including pointers to char)) are uninitialised, unless they are statics. So are arrays of "primitive types". That means they all potentially contain "garbage values".
The std::string
type in the standard library is a (templated) class type that, when default constructed, is initialised to the empty string in all circumstances.
The rules for struct and class types are a bit more complicated but, in simple terms, the initialisation depends on workings of the relevant constructor.
Upvotes: 1
Reputation: 842
std::string's default constructor, "Constructs an empty string, with a length of zero characters."
http://www.cplusplus.com/reference/string/string/string/
If you have an object (class) with a mix of primitives and non-primitives, the default constructors of the non-primitives are called, and the primitives behave just like the would if they were not members of a class. That is, you'll need to initialize them (in the object's constructor, preferably with an initialization list). (http://www.cprogramming.com/tutorial/initialization-lists-c++.html)
Upvotes: 3
Reputation: 726489
Are [strings] assigned some garbage value too? What about other primitive types?
String of C++ Standard Library (i.e. std::string
) is not a primitive type. Unlike primitive types, it has a constructor, which will be invoked when you do not specify any value.
Primitive types like int
, long
, char
, on the other hand, remain uninitialized, unless you provide an explicit initializer, or place them in static memory (in which case they are zero-initialized).
Upvotes: 5