-2

this is my very first post and please understand if formatting is bad X)

So, in my class, I was required to use operator= function to make a class object equal to the second object of the same class.

class Car
{
private :
    int a;
    int b;
public :
    void set(int x, int y)
    {a = x;
     b = y;
    }

    void output()
    {cout << a << " " << b << endl;
    }

    Car & operator=(const Car & carB)
    {set(int c, int d);
    }
};

using namespace std;
int main()
{
 Car car1(1, 2);
 Car car2;

 car2=car1;
 car2.output();

 return 0;
}

I understand that Car & operator=(const Car & carb) function allows me to make the car2 equal to car 1. However, I'm not quite understanding the type of the function here. Why is the function not void? And what does the reference signs(both) do in this code?

I am on my 2nd quarter of very first computer language. Please help! Thanks! :]

jvsper
  • 41
  • 4
  • 1
    This code can't possibly compile. Please edit it so that it does and ask again. –  Jun 02 '18 at 23:40
  • Because it is a function call that returns a Car object and assigns it...., that is why it is not void – Omid CompSCI Jun 02 '18 at 23:41
  • 2
    Possible duplicate of [Why must the copy assignment operator return a reference/const reference?](https://stackoverflow.com/questions/3105798/why-must-the-copy-assignment-operator-return-a-reference-const-reference) – Fureeish Jun 02 '18 at 23:42

2 Answers2

2

This is called assignment operator, and you don't need to implement it as it is by default exists. If you have pointers in the class you can implement your own assignment operator and copy constructor to do deep copy instead of shallow copy.

The reference sign mean return by reference which allows function calls to be on the left hand side of the call, and allows cascading assignment like A = B = C.

last thing...your code in the assignment operator is wrong. It should be like this:

set(carB.a, carB.b);
0

The type of the function is not void because C++ allows statements like this:

A = B = C;

After the execution of this statement, all three variables will have the same value. In other words,

A = (B = C);

which demands that B=C return a thing of the same type as A.

As for what the reference symbol ('%') does, look it up in your textbook.

Beta
  • 96,650
  • 16
  • 149
  • 150