is it okay to call the overrided assignment function in copy constructor

Discussion in 'C++' started by jccpro, Aug 15, 2005.

  1. jccpro

    jccpro Guest

    as the following code shows:

    class A {
    public:
    A(const A & rhs) {
    *this = rhs;
    }

    A & operator=(const A & rhs) {
    if (this != &rhs) {
    ...
    ...
    }
    return *this;
    }
    };
     
    jccpro, Aug 15, 2005
    #1
    1. Advertisements

  2. I see a couple of reasons why it might not be OK. First of all, the
    object ('*this') hasn't been fully constructed until the constructor body
    finishes executing and returns. That means that something can still be
    unfinished about this object. The assignment operator, OTOH, assumes that
    the object for which it's called is complete. That's a theoretical no-no.
    Another, rather practical no-no, is if you try to use any virtual
    function in the assignment operator. Especially if you declare them
    pure in class A.

    V
     
    Victor Bazarov, Aug 15, 2005
    #2
    1. Advertisements

  3. The behaviour of the code above is well defined and probably what you
    expect.
     
    Gianni Mariani, Aug 15, 2005
    #3
  4. jccpro

    Earl Purple Guest

    There can be issues with doing it that way if operator=() calls new and
    it fails either with bad_alloc or because the object you create throws
    an exception

    That is why the preferred way is to get operator= to call the
    copy-constructor and swap. Thus:

    class A
    {
    public:
    A( const A & ); // well defined
    void swap( A& ); // well defined, possibly private

    A& operator=( const A& rhs )
    {
    A temp( rhs );
    swap( temp );
    return *this;
    }
    };

    There is no need to check here for self-assignment either. While it
    would be more efficient to check for it when you are self-assigning,
    99.9% of the time you are not and on those occasions you are making a
    saving by not checking for it.
     
    Earl Purple, Aug 15, 2005
    #4
  5. jccpro

    jccpro Guest

    If there are some potential issues, I would rather declare an
    initialize method to be called by both copy constructor and assignment
    operator as below:

    class A {
    public:
    A(const A & rhs) {
    initialize(rhs);
    }

    A & operator=(const A & rhs) {
    initialize (rhs);
    return *this;
    }

    void initialize (const A & rhs) {
    ...
    ...
    }
    };
     
    jccpro, Aug 15, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.