Why default constructor initialises memeber variables with garbage values if its not defined ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why default constructor initialises memeber variables with garbage values if its not defined ?

Please can you also provide the definition of the default constructor the computer understands if we do not define it manually .

23rd Sep 2018, 11:44 AM
Aman Jain
Aman Jain - avatar
4 Answers
+ 1
If they are not initialised, then what's the use of the default constructor if we haven't defined it manually ?
23rd Sep 2018, 1:24 PM
Aman Jain
Aman Jain - avatar
+ 1
Well, it "introduces" the object to the compiler, allocates the required memory behind the scenes and calls the default constructor for its members (if it has any).
23rd Sep 2018, 3:39 PM
Shadow
Shadow - avatar
0
It's actually the other way round. The member variables are not initialized with garbage values, they have garbage values because they are not initialized. This is because in most (not all) cases, the default constructor is trivial, i.e. it performs no action: Foo::Foo() {} However, there are also cases when the default constructor is not trivial, you can read about them here: https://en.cppreference.com/w/cpp/language/default_constructor
23rd Sep 2018, 12:30 PM
Shadow
Shadow - avatar
0
But the computer understand the default constructor as- class_name() { }; This contain an empty body. How does the compiler interpret it ?🤔
23rd Sep 2018, 5:37 PM
Aman Jain
Aman Jain - avatar