I have fallen into the belief that variables are assigned their default values when using brace initialization. But I was wrong.
In the following example:
#include <string>
#include <iostream>
#include <stdint.h>
class A
{
public:
A() {}
~A(){}
int var1;
int32_t var2;
int64_t var3;
std::string var4;
double var5;
float var6;
std::string info() const {
return "var1=" + std::to_string(var1) + " " +
"var2=" + std::to_string(var2) + " " +
"var3=" + std::to_string(var3) + " " +
"var4=" + var4 + " " +
"var5=" + std::to_string(var5) + " " +
"var6=" + std::to_string(var6) + " " +
"\n"
;
}
};
int main()
{
A a;
std::cout << "Before assigning variables: " << a.info();
a.var1 = 1;
a.var2 = 2;
a.var3 = 3;
a.var4 = "4";
a.var5 = 5;
a.var6 = 6;
std::cout << "After assigning variables: " << a.info();
a = {};
std::cout << "After brace init assignment: " << a.info();
}
Here is the result:
Before assigning variables: var1=0 var2=0 var3=4198240 var4= var5=0.000000 var6=0.000000
After assigning variables: var1=1 var2=2 var3=3 var4=4 var5=5.000000 var6=6.000000
After brace init assignment: var1=2114725200 var2=32766 var3=4199416 var4= var5=0.000000 var6=0.000000
To fix it:
- If I get rid of the default constructor - the problem goes away.
If a class's member variable is brace-initialized, then it will be assigned 0 or the default value. E.g.:
class A { public: A() {} ~A(){} int var1{}; int32_t var2{}; int64_t var3{}; std::string var4{}; double var5{}; float var6{}; };
Can someone please explain why this happens? What am I missing here?
A
has a user-defined constructor, soA{}
means to call the constructor and nothing more. Maybe you are mixing up this case with other examples where there is no user-defined constructor (in which caseA{}
can mean to initialize each member variable as if by{}
). – Leduc