yejep
yejep

Reputation: 9

constructor and the assignment operator

Can I write a copy constructor through the assignment operator? Like this:

A::A(const A * a) {
    *this = a;
}

A &A::operator=(const A * a) {
    delete str;
    str = new char[strlen(a->str)+1];
    strcpy(str, a->str);
    return *this;

}

Still want to clarify whether if I do A * a in the above example, because samples from different sites A & a. C This pops up a question that should return the assignment operator:

A &A::operator=(const A * a)

or

A * A::operator=(const A * a)

General question: Is my code right above?

Upvotes: 0

Views: 82

Answers (2)

Mark B
Mark B

Reputation: 96233

The best solution is to make str be a std::string and then you don't need to write your own copy constructor OR copy assignment operator.

But let's say you have to write your own for non-obvious reasons you can't share with us.

In that case, a typical approach to provide some exception safety is to implement a nothrow swap function, and then implement copy assignment in terms of copy construction + swap (the opposite of what you're proposing, but provides much better exception safety for the copy assignment)

Upvotes: 3

Tomek
Tomek

Reputation: 4659

Both of them have different signature:

A::A(const A &a);
A &A::operator=(const A &a);

What you are writing is not copy constructor nor assignment operator.

Look for copy-and-swap idiom, this is what allows you to write copy assignment in terms or copy construction.

Upvotes: 0

Related Questions