Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Class C++ can be equal to a variable

Tags:

c++

I have this code:

#include <iostream>
using namespace std;

class complex
{
    double re;
    double im;

public:
    complex(): re(0), im(0) {}
    complex(double x) {re = x, im = x;}
    complex(double x, double y) {re=x, im =y;}
    void print() {cout << re << " " << im;}
};

int main()
{
    complex c1;
    double i=2;
    c1 = i;
    c1.print();

    return 0;
}

My question is, why the code in this line compiles.

c1 = i;

The compiler gives no error(or warning), why?

like image 854
Joc380 Avatar asked Jul 05 '26 11:07

Joc380


2 Answers

Let's examine what happens in the line.

c1 = i;

What happens is that operator= is called for class complex, which, in this case, is implicitly defined.

/////////////////////////////////////
//implicit copy assignment operator//
/////////////////////////////////////

complex& operator=(const complex& cmp)
{
    //the default implicit function of this operator is copying every member of cmp into this.
}

So it takes const complex& as argument, which can be bound to rvalue of type complex, then the compiler searches to see if there is a constructor accepting double parameter, so the expression is resolved into.

c1 = complex(i);

Which, obviously, can be executed.

like image 106
Karen Baghdasaryan Avatar answered Jul 08 '26 01:07

Karen Baghdasaryan


c1 = i invokes the constructor complex(double x) {re = x, im = x;}. If you'd prefer it didn't you can specify the constructor as explicit, like so:

explicit complex(double x) {re = x, im = x;}

Then the compiler would issue an error @ c1 = i;

like image 29
KeyC0de Avatar answered Jul 08 '26 00:07

KeyC0de