assignment operator for classes
Getting a little confuse on this part.
I give an example:
Class A{
char *str;
int number;
public:
set(int);
printnumber();
};
int main()
{
A b;
int x =3;
b.set(x);
A c(&b) /*this calls copy constructor which is grand
A d = c /*this calls copy consturctor which is grand
A e;
e=b; /*doesnt call copy constructor*/
e.printnumber();
My question is what does the assignment operator do? Does it just copy the values across from B?
HOw is it different to the copy constructor?
Why do we need to overload the assignment operator if we overload the copy constructor?
I know it will print the value 3 out.
Thanks
Re: assignment operator for classes
There is a difference between constructing a new object and assigning a new value to an existing object.
Code:
class A {};
void func()
{
A first; // calls default constructor to make a new A called first.
A copy_of_first( first ); // calls copy constructor to construct a new A thats a direct copy of first.
A second;
first = second; // this is assignment. We dont create first, we just give it a new value
A third = second; // this is initialisation. Its a copy constructor call.
}
I hope that clears things up a bit.
Re: assignment operator for classes