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

J

jccpro

as the following code shows:

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

A & operator=(const A & rhs) {
if (this != &rhs) {
...
...
}
return *this;
}
};
 
V

Victor Bazarov

as the following code shows:

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

A & operator=(const A & rhs) {
if (this != &rhs) {
...
...
}
return *this;
}
};

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
 
G

Gianni Mariani

as the following code shows:

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

A & operator=(const A & rhs) {
if (this != &rhs) {
...
...
}
return *this;
}
};

The behaviour of the code above is well defined and probably what you
expect.
 
E

Earl Purple

as the following code shows:

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

A & operator=(const A & rhs) {
if (this != &rhs) {
...
...
}
return *this;
}
};

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.
 
J

jccpro

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) {
...
...
}
};
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top