According to many references, when you write Myclass C; it wil use the default ctor, which does not do any initialization and so should leave C's members as garbage. So why is it that STL classes are value-initialized ?
Asked
Active
Viewed 69 times
-5
-
3Who says the default constructor should leave the object uninitialized? That would make it unusable, wouldn't it? – DeiDei May 24 '17 at 10:24
-
For example : https://stackoverflow.com/questions/2417065/does-the-default-constructor-initialize-built-in-types – Aaa Bbb May 24 '17 at 10:25
-
1`string` is not a built-in type. – themiurge May 24 '17 at 10:26
-
Either many references are wrong, or you misread them. – juanchopanza May 24 '17 at 10:27
-
The first answer in the link you posted answers it. – DeiDei May 24 '17 at 10:27
-
It is not a built-in type, but as I understand the default ctor will recursively call default ctors of subobjects until we reach basic types such as int which will be left underminate – Aaa Bbb May 24 '17 at 10:28
-
The first answer says that C c; // Compiler-provided default constructor is used // Here `c.x` contains garbage which is inconsitant with the fact that string s; contain well determined value – Aaa Bbb May 24 '17 at 10:28
-
Because `std::string` performs some intializations in its default constructor implementation? – songyuanyao May 24 '17 at 10:29
-
`string`'s default constructor creates an empty string. See [here](http://en.cppreference.com/w/cpp/string/basic_string/basic_string). – themiurge May 24 '17 at 10:33
1 Answers
2
When you write MyClass C;
the compiler generates code that calls the default constructor for your class MyClass
. The "default constructor" is the constructor that can be called with no arguments, and the effect of calling it is whatever that constructor does. If you leave it up to the compiler to generate the default constructor, then, yes, members that have builtin types don't get initialized. If you write your own default constructor you can initialize whichever members you think appropriate. That's what std::string
does: it sets up the string object so that it holds an empty string.
class MyClass {
public:
MyClass() : member(3) {} // default constructor
int member;
};
MyClass C; // C.member has the value 3

Pete Becker
- 74,985
- 8
- 76
- 165
-
I thought default constructor meant "compiler generated constructor". Hence the reason for my confusion. – Aaa Bbb May 24 '17 at 20:37