Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling a C++ constructor without parameter does not set values to 0

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) {}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading