Thread: Copy Constructors and Assignment Operator overloading.

  1. #1
    Registered User
    Join Date
    Apr 2004
    Location
    Ohio
    Posts
    147

    Copy Constructors and Assignment Operator overloading.

    I think this should be a fairly straight-forward question.

    I generally understand why one would use copy constructors and assignment operator overloading -- deep copies. But I've never used them up until this point.

    I'm trying to figure out how I would build the appropriate constructors/operator overloads when I want to 'deep copy' two pointers to an object. Example:

    Code:
    class foo
    {
    public:
        foo(int x) : mInt(new int(x))
        {}
    
        int getVal() { return *myInt; }
    private:
        int *myInt;
    }
    Assuming that 'myInt' is properly initialized and destroyed during construction/destruction, I now want to use the class as follows:

    Code:
    void someFunc()
    {
        foo *bar1 = new foo();
    
        foo *bar2 = bar1;
    
        delete bar1;
        bar1 = NULL;
    
        std::cout << bar2->getVal(); // crash as bar2 is not an independant object, just a shallow copy of bar1
    }
    Now I understand that I need to do a deep copy of sorts and I know that there are a variety of ways to build copy constructors and operator assignment overloads... I'm just not sure which one/s to use. I've looked around on google and came across some explanations that were seriously lacking and others that were just plain wrong or didn't cover my particular case where I'm copying pointer of objects.

    Thanks for taking the time to read my question.
    Last edited by leeor_net; 11-09-2009 at 10:15 PM. Reason: forgot the return type on getVal()

  2. #2
    Registered User
    Join Date
    Apr 2004
    Location
    Ohio
    Posts
    147
    I realized all of a sudden that I'm not dereferencing the pointers to the object foo. Upon doing that (e.g., *bar2 = *bar1), problem is solved.

    My concern at this point is what other pitfalls I should be aware of.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. assignment operator for static array inside a class
    By acosgaya in forum C++ Programming
    Replies: 3
    Last Post: 07-27-2008, 11:11 AM
  2. Doing maths to copy constructed variables
    By Paul Skinner in forum C++ Programming
    Replies: 7
    Last Post: 12-11-2007, 05:31 PM
  3. Hiding constructors, exposing copy operations
    By Mario F. in forum C++ Programming
    Replies: 10
    Last Post: 07-23-2007, 07:44 AM
  4. Copy constructors and operator=()
    By filler_bunny in forum C++ Programming
    Replies: 13
    Last Post: 08-25-2003, 07:43 AM
  5. Replies: 2
    Last Post: 12-17-2001, 06:40 PM