|
-
September 1st, 2009, 09:37 AM
#1
Basic Question from newbie... - Copy Constructors
Hi everyone,
First post on this forum so hope this is in the right place, please advise if not.
I'm relatively new to C++ and have been trying to test my knowledge with some online tests. I'm a little stuck on one question about copy constructors and in exactly what situations they are invoked, can anyone shed any light on which of the following they are used:
1 - When an existing object is assigned an object of its own class
2 - When a function receives as an argument, an object of the class by value
3 - When no conversion function exists for converting the class to another class object
4 - When a function returns an object to the class by value
5 - When creating an object and initialising it with an object of its own class
I think it would be in called in 2 and not in 4 but other than that I'm unsure, any help appreciated!
Thanks!
-
September 1st, 2009, 09:46 AM
#2
Re: Basic Question from newbie... - Copy Constructors
"A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object."
Wikipedia
My guess would be 5.
-
September 1st, 2009, 09:49 AM
#3
Re: Basic Question from newbie... - Copy Constructors
Thanks for the reply Skizmo, it can be more than one of those options, up to three I think...
I thought that when an object was passed by value a copy of it was made, hence 2.
Would agree with you about 5 though!
-
September 1st, 2009, 11:03 AM
#4
Re: Basic Question from newbie... - Copy Constructors
1) would use an assignment operator.
2) Yes, passing by value means creating a new object and copying the value.
3) This would be a cast operator
4) Returning by value means returning a new (temporary) object which is constructed and copied at the end of the function.
5) yes, duh.
-
September 1st, 2009, 11:24 AM
#5
Re: Basic Question from newbie... - Copy Constructors
Great, so it's 2,4 and 5. Thanks for your help!
-
September 1st, 2009, 11:25 AM
#6
Re: Basic Question from newbie... - Copy Constructors
Be careful about (1). Sometimes the assignment operator is implemented in terms of the copy constructor. That isn't automatic though.
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
|