I’ve build a class representing a matrix and I override all
the arithmetic operators. Here’s an example of overloading the unary minus
RegMatrix.h:
const RegMatrix operator - ();
RegMatrix.cpp
const RegMatrix RegMatrix::operator - ()
{
RegMatrix newMatrix(*this);
newMatrix *= -1;
return newMatrix;
}
Now, this works perfect when I instantiate object on the stack like this: RegMatrix a(3,3,v) (v is a vector of values, doesn’t matter).
When I use the new keyword like this (in main.cpp):
RegMatrix* a = new RegMatrix(3,3,v);
RegMatrix* b = -a; //<---ERROR HERE
I get wrong type argument to unary minus
Any ideas why this happens? Thanks!
P.S.
Another question: the ‘=’ operator is automatically overridden by the copy constructor, right?
The type of
aisRegMatrix *, notRegMatrix; if you want to apply operators on the object to whichapoints you have to dereferencea(*a), apply the operator to it (-(*a)) and, if you want a separate instance of it on the heap, create a new copy of it on the heap withnewand the copy constructor:Still, as @leftaroundabout pointed out in a comment, this is not a good way to work in C++, where, as a rule of thumb, you try to avoid dynamic allocation if you can (it’s slower and it requires smart pointers if you don’t want memory leaks).