CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Sep 2009
    Posts
    19

    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!

  2. #2
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    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.

  3. #3
    Join Date
    Sep 2009
    Posts
    19

    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!

  4. #4
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    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.

  5. #5
    Join Date
    Sep 2009
    Posts
    19

    Re: Basic Question from newbie... - Copy Constructors

    Great, so it's 2,4 and 5. Thanks for your help!

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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
  •  





Click Here to Expand Forum to Full Width

Featured