Somebody gave me a a program having an error yesterday. Working in MVS 2010, I found the problem and an alternative for it as well. The problem was the overloaded insertion operator the class. Its prototype was as follows...
void matrix :: operator << (matrix&) ;
It was called from somewhere like this...
matrix m ;
m.operator << (m) ;
I worked out that compiler does not allow to send the same object as a reference parameter upon which the function was called. But I don't understand the reason behind that and that what problem does it create. I would appreciate if anybody could explain that. Thanks.
EDIT:
What is actually happening is that upon debugging, it goes inside the function, comes out and at execution of main
, goes into the external dependency file dbgdel.cpp
and stops at this line.
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
In C++, we can change the way operators work for user-defined types like objects and structures. This is known as operator overloading.
Function Overloading in C++ You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
Because if you do not, then the actual object will not be modified. Instead a copy will made and the copy will be modified, then later the copy will get destroyed.
Overloaded operators are just functions (but of a special type) with a special keyword operator followed by the symbol of the operator to be overloaded.
The code given compiles and runs just fine in VS2010 SP1
.
There's no issue with the code as shown either, it's perfectly legal. I's a little odd to declare an operator overload and then call it with operator <<
, as you could just as easily write m << m
.
Some guesses:
m
somewhere in the operator implementation and accidentally deleting it Seems like your program is telling you the heap is corrupted: at some point it has gone over the bounds of an array or written to memory via a pointer that was freed, or something like that.
These bugs can be hard to track down, as you don't know exactly when it happened, but it is very likely it happened in a different place to where the error showed up. There is no problem with using reference parameters in the way you have.
There are a bunch of suggestions for how to detect heap corruption here:
Heap corruption under Win32; how to locate?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With