-
March 4th, 2009, 02:01 PM
#1
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
-
March 4th, 2009, 02:29 PM
#2
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.
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
-
March 4th, 2009, 03:54 PM
#3
Re: assignment operator for classes
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|