I’m somewhat new to C++ so, I guess this is a very basic question.
Suppose I have this class:
// file Graph.h
class Graph {
public:
Graph(int N); // contructor
~Graph(); // destructor
Graph& operator=(Graph other);
private:
int * M;
int N;
};
// file Graph.cpp
Graph :: Graph(int size) {
M = new int [size];
N = size;
}
Graph :: ~Graph() {
delete [] M;
}
I want to create an assignment operator that will copy the contents of array M[] but not to overwrite it when I change it after the copy (I think this is accomplished by not copying the actual pointer but only the content, don’t know if I’m right). This is what I’ve tried:
Graph& Graph::operator=(Graph other) {
int i;
N = other.N;
M = new int [N];
for (i = 0; i < N; i++)
M[i] = other.M[i];
return *this;
}
Is this correct? Are there other ways to do this?
edit: An important question I forgot. Why I must declare it like Graph& operator=(Graph other); and not just: Graph operator=(Graph other); which is what’s written in my book (C++: The Complete Reference, 2nd ed, Herbert Schildt, pages 355-357)?
The canonical way is to use a
std::vector<int>to avoid managing memory yourself. For the exercise though, the right way to do what you want is:Google “copy and swap idiom” for the rationale behind the code. Note that your assigment operator leaks memory (the original array is overwritten but never deleted) and if the allocation fails, you end up with a broken object. Moreover,
x = xwon’t do what it is expected to do. These three pitfalls are common, and writing assignment operators in copy-and-swap style avoids them.EDIT: For your other question, returning a reference allows you to chain assignments, like
a = b = c, which is valid for built in types. It may or may not be what you want (it usually is).