The comments answered your particular question, but there are a few other issues you may want to consider.
If you define a copy constructor and copy assignment operator, you
probably also need to define a destrcutor. This is known as the rule
of three/five. In the
posted code that means you need a destructor to delete the allocated
memory.
Also, in order to ensure exception safety, you may also want to
consider using the copy and swap
idiom. This also allows
the copy assignment operator to be written in terms of the copy
constructor eliminating the need to write a separate copy
function
that is used by both.
Lastly, in modern C++
there are very few instances that call for
using raw pointers. Since this class presumably owns the data in x
,
a std::unique_ptr
would accurately indicate the intended owership
and simplify managing the memory.
Sample Code
// Rule of three with copy-and-swap idiom
class A {
public:
A() {
x = new int[10];
}
A(const A& other) : A() {
std::copy(other.x, other.x + 10, x);
}
const A& operator=(A other) {
std::swap(*this, other);
return *this;
}
~A() {
delete x;
}
private:
int *x{nullptr};
};
// Copy-and-swap idiom using a unique pointer
class AUP {
public:
AUP() {
x = std::make_unique<int[]>(10);
}
AUP(const AUP& other) : AUP() {
std::copy(other.x.get(), other.x.get() + 10, x.get());
}
const AUP& operator=(AUP other) {
std::swap(*this, other);
return *this;
}
private:
std::unique_ptr<int[]> x;
};
int main() {
A a;
A b = a;
AUP aup;
AUP bup = aup;
}