0

I have a problem with constructor and assignment operator. This is my code:

class Class
{
    private:
        double number1;
        double number2;
    public:
        Class(double, double);
        Class& operator=(const Class& n);
}

Class::Class(double n1 = 0.0, double n2 = 0.0)
{
    this->number1 = n1;
    this->number2 = n2;
}

Class& operator=(const Class& n)
{
     this->number1 = n.number1;
     this->number2 = n.number2;
     return *this;
}

int main()
{
    Class n1(2., 3.), n2(7., -1.), n3();

    n2 = n1; // no problem
    n3 = n1; // problem

    return 0;
}

Can you please enlight me, why is there a problem with the second assignment in the main?

Thank you very much

edit: The following error occurs:

[Error] assignment of function 'Complex cislo2()'
[Error] cannot convert 'Complex' to 'Complex()' in assignment
Adam
  • 111
  • 1
  • 1
  • 3

1 Answers1

2

amon's comment is correct.

To explain it simply, in the sample code you provided:

Class n3();

Defines a function that takes no arguments, and returns an instance of Class by value.

It is a quirk in the C++ syntax.

To workaround this error, omit the empty parenthesis pair when initializing variables that does not take any constructor parameters.

Community
  • 1
  • 1
rwong
  • 6,062
  • 1
  • 23
  • 51