Domanda

I try to write a simple code to understand how overloading operators and copy constructor works. But I stacked in one place. Here is my code

 #include <iostream>
 using namespace std;

 class Distance
 {
    private:
       int feet;             
       int inches;           
    public:
       // required constructors
       Distance(){
          feet = 0;
          inches = 0;
       }
       Distance(int f, int i){
          feet = f;
          inches = i;
       }
       Distance(Distance &D){
          cout<<"Copy constructor"<<endl;
          this->feet = D.feet;
          this->inches = D.inches;
       }
       // overload function call
       Distance operator()(int a, int b, int c)
       {
          Distance D;
          // just put random calculation
          D.feet = a + c + 10;
          D.inches = b + c + 100 ;
          return D;
       }

 };
 int main()
 {
    Distance D1(11, 10);
    Distance D2 = D1(10, 10, 10); // invoke operator() why here copy constructor is not called
    return 0;
 }

My question is that : Why in this line of main

Distance D2 = D1(10, 10, 10); // invoke operator() why here copy constructor is not called

Copy constructor is not called. Should not it firstly invoke overloading operator and afterwards go to copy constructor? Why does it give error?

È stato utile?

Soluzione

This is because D2 already exists. You have created it just line above with

Distance D1(11, 10), D2;
                     ^

So the meaning of the = is operator=. The object is assigned new value ( this new value results from a call to operator() ( int, int, int) on D1) and not created ( constructed) with some value.

To call a copy constructor you need to assign a value to object in the line of its creation

int main() {
    Distance D1(11, 10);
    Distance D2( D1);   // calls copy ctor
    Distance D3 = D1;   // calls copy ctor
    return 0;
}

but

int main() {
    Distance D1(11, 10);
    Distance D2;
    D2 = D1;   // calls operator=
    return 0;
}

Altri suggerimenti

Here:

D2 = D1(10, 10, 10);

You call the operator() in D1(10, 10, 10) and then you are calling operator=.

If you want to call a copy constructor, you need do the following:

Distance D2(D1);

Just a tip: take a look on the copy constructor signature - it shows exactly how you should call it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top