I'm kind of new in C++, only about a week in. I'm using VS10 for writing my exercises from a C++ book. I have previous C experience but does not seem to help too much in understanding the run-time errors I'm getting.
I wrote a class called student that has constructors, destructor and some other pretty trivial member methods (not to say functions).
Among other things, I'm overwriting the + operator in such a way:
The reason I'm putting this here is because the error seems to be popping when the return command in the operator overwrite is executed and this calls the constructor and destructor - I don't know why exactly.
So the program runs OK if I ignore the error. I don't get a very specific error just that some violation in the heap had occurred. If someone will further direct me I might be able to pull out a better error report.
"delete name, grades;" doesn't do what you think it does: it is a comma operator separating the expressions "delete name" (which, when executed, frees the memory pointed to by name), and the expression "grades", which, when executed, does nothing at all.
But that's just a memory leak, not a runtime crash. Seeing as you had to define an assignment operator and a destructor, the first question is: how did you define the copy constructor? and, seeing as you're relying on vec.name to be valid C string, how did you define other constructors?
If helps to post a complete, compilable, minimal example, when you have a problem you want someone else to debug.
This doesn't do what you think. It does not delete both name and grades... it only deletes one of them (I forget which ... the comma operator is weird).
In general... the comma operator doesn't do what you think it does. Avoid it.
A heap error sounds like you are trying to dereference a pointer after it's deleted... or are deleting something that had already been deleted. It's hard to say without being able to repro the error (if you run from the debugger, it should tell you exactly what line it's happening on)
So long story short... you are screwing up your memory management somehow.
But you shouldn't be doing manual memory management anyway. C++ offers containers for all this stuff.
Instead of using a char*, you should be using a string.
Instead of using a int*, you should be using a vector<int>.
If you do that, you do not need to overload the = operator, or destructor... or have to do any memory management. All of it will be done automatically.
Can you post the student class in full? That would help me spot the error.
This is an exercise from a book, so naturally at this stage some less than ideal concepts are being exercised to prove a point or something similar :)
Adding the two students means to take the longer name, higher age and longer grade list + adding the shorter grade list to the new one. This is actually performed as should and I can see the output is as desired if I ignore the error.
yes - the sizeof was actually a mistake!!! :) Thanks