lundi 24 décembre 2018

overloading typecast operator

Overloaded typecast operator int, but after compiling and running the code I get segmentation fault.

I debugged my program and saw that line of code where typecast is used repeats without ending, every time calling typecast function itself. So, can anyone explain what's going on around there ?

/* IN HEADER */
class ComplexNumber
{
private:
    double m_real, m_imaginary;

public:
    ComplexNumber(double real = 0.0, double imaginary = 0.0);
    ComplexNumber(const ComplexNumber &obj);

    ComplexNumber& operator= (const ComplexNumber &obj);

    operator int();

};

ComplexNumber::ComplexNumber(double real, double imaginary): 
    m_real(real), m_imaginary(imaginary)
{

}

ComplexNumber::ComplexNumber(const ComplexNumber &obj): 
m_real(obj.m_real), m_imaginary(obj.m_imaginary)
{

}

ComplexNumber& ComplexNumber::operator= (const ComplexNumber &obj)
{
    m_real = obj.m_real;
    m_imaginary = obj.m_imaginary;

    return *this;
}

ComplexNumber::operator int()
{
    m_real = static_cast<int>(m_real);
    m_imaginary = static_cast<int>(m_imaginary);

    return *this;
}

/* IN MAIN */
ComplexNumber obj(3.4, 5.6);

obj = static_cast<int>(obj);
//here it gives seg fault

Aucun commentaire:

Enregistrer un commentaire