Can someone explain why my constructor is not setting Fraction c,d,e values to 0 when no parameter is provided? Results are: Fraction c=0,0 d=0,6e23 e=6e23,0.
I have found the workaround of setting Fraction::Fraction() {} to Fraction::Fraction() : m_num(0), m_deno(0) {} but I thought using Fraction::Fraction() {} would mean filling the values with 0s…
class Fraction {
public:
Fraction(double num, double deno);
Fraction(double num);
Fraction();
private:
double m_num;
double m_deno;
};
int main() {
Fraction a(4,5); // a=4/5
Fraction b(2); // b=2/1
Fraction c, // c=0/0
d, // d=0/6e23
e; // e=6e23/0
return 0;
}
Fraction::Fraction() {}
Fraction::Fraction(double num) : m_num(num), m_deno(1) {}
Fraction::Fraction(double num, double deno) : m_num(num), m_deno(deno) {}
>Solution :
If you do not assign default values to C++ default types (for example: int, float, char) class variables inside the constructor, they are not going to be defaulted to zero. That will lead you to undefined behaviour.
Check here to see in which cases the variables will be zero: Default initialization in C++
If you want them to be zero:
private:
double m_num = 0;
double m_deno = 0;