![]() |
|
#1
|
|||
|
|||
Why the destructor is called?Hello everyone!
I'm coding an application and I don't understand why it isn't working. I've written a simple example to show you my problem: CPP / C++ / C Code:
The problem is that when I do "t = a + b;" the "return z" in the function "test operator+(test&, test&);" it calls the destructor for z before it returns and this makes a crash because the variable t doesn't have anything. Also, the destructor for "t" is called right after the return from the function causing another crash. The interesting part is that if I adapt the code to sum vectors intead of matrices, it works! Any help would be appreciated. Thanks, scherzo Last edited by LuciWiz : 22-Oct-2007 at 14:27.
Reason: Please insert your C/C++ code between [cpp] & [/cpp] tags
|
|||
|
#2
|
|||
|
|||
Re: Why the destructor is called?Quote:
The destructor is called when the + operator finishes, since the "test" object (a local variable) is no longer in scope. That's the way it works. The operator returns the object which contains a pointer to memory that is no longer valid. Since you don't have an overloaded assignment operator, the assignment statement just copies the value of the pointer, v, that the + operator used, which is no longer valid. Therefore the crash. Whenever you have a constructor that allocates storage you usually need an overloaded assignment operator and a copy constructor to take care of things like this. Regards, Dave |
|
#3
|
|||
|
|||
Re: Why the destructor is called?Thanks for all davekw7x, I solved my problem now.
Best regards, scherzo |
Recent GIDBlog
Programming ebook direct download available by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| a tester class and then some. | postage | Java Forum | 1 | 06-May-2006 16:48 |
| 1 line php cover function changes result of called programs | schgid | MySQL / PHP Forum | 0 | 03-May-2005 11:15 |
| How do I check whether the object q1 exists? ie: q1=new queue has been called? | wc3promet | C++ Forum | 1 | 15-Oct-2004 10:15 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The