Search code examples
c++oopoperator-overloadingruntime-errorinsertion

Passing an Object to Overloaded Operator


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));

Solution

  • 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:

    • You are taking the address of m somewhere in the operator implementation and accidentally deleting it
    • You are overrunning the boundaries of the array of values that is probably stored in the matrix, inside the operator implementation.
    • There's a mismatch in the compiler and linker assumptions between the calling code and the called code. Check your calling conventions, version of the runtime libraries on both sides, and any other settings such as SECURE_SCL and interator debugging.