473,395 Members | 1,578 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Why doesn't destructor work?

3
Hello! I have a code:
Expand|Select|Wrap|Line Numbers
  1. // class Polynomial
  2. // Constructor, Destructor
  3. // Friend Function, Operator Overloading
  4. #include <iostream.h>
  5.  
  6. class Polynomial
  7. {
  8.     private:
  9.     int n;        // Degree of polynomial
  10.     double* p;    // Pointer to array contains 
  11.                 // coefficients of polynomial
  12.  
  13.     public:
  14.     Polynomial();
  15.     Polynomial(int n1);
  16.     ~Polynomial();
  17.  
  18.     friend ostream& operator<< (ostream& os, const Polynomial& pol);
  19.     friend istream& operator>> (istream& is, Polynomial& pol);
  20.  
  21.     // plus two polynomials
  22.     Polynomial operator+ (const Polynomial& daThuc2);
  23. };
  24.  
  25. Polynomial::Polynomial()
  26. {
  27.     this->n = 0;
  28.     this->p = NULL;
  29. }
  30.  
  31. Polynomial::Polynomial(int n1)
  32. {
  33.     this->n = n1;
  34.     this->p = new double[n1+1];
  35.     if(NULL == p)
  36.     {
  37.         cout << "Not enough memory.";
  38.         exit(1);
  39.     }
  40. }
  41.  
  42. Polynomial::~Polynomial()
  43. {
  44.     this->n = 0;
  45.     delete this->p;
  46. }
  47.  
  48. ostream& operator<< (ostream& os, const Polynomial& pol)
  49. {
  50.     os << "Coefficients of the polynomial( from ao ): ";
  51.     for(int i = 0; i <= pol.n; ++i)
  52.         os << pol.p[i] << " ";
  53.     os << endl;
  54.     return os;
  55. }
  56.  
  57. istream& operator>> (istream& is, Polynomial& pol)
  58. {
  59.     cout << "Enter degree of polynomial: ";
  60.     is >> pol.n;
  61.     pol.p = new double[pol.n+1];
  62.  
  63.     cout << "Enter coefficients of the polynomial( from ao ): ";
  64.     for(int i = 0; i <= pol.n; ++i)
  65.         is >> pol.p[i];
  66.  
  67.     return is;
  68. }
  69.  
  70. Polynomial Polynomial::operator+ (const Polynomial& pol2)
  71. {
  72.     int n1 = n > pol2.n ? n : pol2.n;
  73.     Polynomial polSum(n1);
  74.     int i = 0;
  75.     while(i <= n1)
  76.     {
  77.         if(i <= n && i <= pol2.n)
  78.             polSum.p[i] = p[i] + pol2.p[i];
  79.         else if(i <= n)
  80.             polSum.p[i] = p[i];
  81.         else
  82.             polSum.p[i] = pol2.p[i];
  83.         ++i;
  84.     }
  85.  
  86.     i = n1;
  87.     while(i > 0 && 0 == polSum.p[i])
  88.         --i; 
  89.     polSum.n = i;
  90.     return polSum;
  91. }
  92.  
  93. int main()
  94. {
  95.     Polynomial f, p, q;
  96.  
  97.     cout << "Enter polynomial p:\n";
  98.     cin >> p;
  99.     cout << "Enter polynomial q:\n";
  100.     cin >> q;
  101.  
  102.     f = p+q;
  103.     cout << "Polynomial f:\n";
  104.     cout << f;
  105.  
  106.     return 0;
  107. }
  108.  
Why does this code run normally?
I think when method "operator+" finishes, the memory which is allocated to polSum will be deallocated by the destructor automatically.
But in this case when I try to compile it, it runs normally. The polynomial f is equal to sum of two polynomial p and q.
In addition, why if I try to change type of p( pointer to array contains coefficients of polynomial ) to int, the result become wrong?
Jan 13 '10 #1
5 2399
newb16
687 512MB
It's deallocated, but before that it's copied by 'return' statement to return value of the same type and then assigned to f in main().
Jan 13 '10 #2
nammae
3
Thank you very much.
But I still don't understand: if the memory which contains coefficients of polynomial is deallocated, why is the result is exact?
Jan 13 '10 #3
Banfa
9,065 Expert Mod 8TB
I think you have undfined behaviour. The internal array is deallocated and since you use the member by member default copy constructor and assignment operator. By the end of main f.p ends up with the same value as polSum.p but polSum.p is deleted as polSum is destructed so f.p ends up pointing to unallocated data. You then access this pointer causing undefined behaviour.

Once you have invoked undefined behaviour all bets are off, anything could happen including getting the results you expected from working code as you have got. However needless to say if you leave the code like this in the end it will go wrong.

You need to implement a copy constuctor and an assignment operator for this class to ensure it copies memory correctly.

Finally on a point of style it is often considered best practice to implement operator+= and then implement operator+ in terms of operator+=, again a copy constructor or operator= is required. For any class T implementing operator+= operator+ is
Expand|Select|Wrap|Line Numbers
  1. T T::operator+(const T& rhs)
  2. {
  3.     return T(*this) += rhs;
  4. }
  5.  
It means you only have to implement and support the addition algorithm once.
Jan 13 '10 #4
weaknessforcats
9,208 Expert Mod 8TB
Problems like this occure due to using a pointer as a member variable and passing to various functions that fiddle with memory. The is usually a recipe for disaster.

I suggest you use a handle class: http://bytes.com/topic/c/insights/65...-smart-pointer
Jan 13 '10 #5
nammae
3
@everyone: Thank you very much.
Jan 14 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

52
by: Newsnet Customer | last post by:
Hi, Statement 1: "A dynamically created local object will call it's destructor method when it goes out of scope when a procedure returms" Agree. Statement 2: "A dynamically created object...
9
by: sahukar praveen | last post by:
Hello, This is the program that I am trying. The program executes but does not give me a desired output. ********************************************** #include <iostream.h> #include...
16
by: Timothy Madden | last post by:
Hy I have destructors that do some functional work in the program flow. The problem is destructors should only be used for clean-up, because exceptions might rise at any time, and destructors...
9
by: Daniel Kay | last post by:
Hello! I have written two template classes which implement the observerpattern in C++. I hope I manage to desribe the problem I have. template<class T> class Observer { /* ... */ }; ...
11
by: Sharon | last post by:
I have heard that if I add a constructor it is not good, it complicates things and that it is better to use the Dispose. Can anybody explain this for me? -- Regards Sharon G.
23
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624....
8
by: gw7rib | last post by:
I've been bitten twice now by the same bug, and so I thought I would draw it to people's attention to try to save others the problems I've had. The bug arises when you copy code from a destructor...
10
by: piboye | last post by:
Hi ! I'm a academician in china. I have been intereted in C++ lasting. In reading the C++ Primer book, i have a trouble about union. In the book ,it said that union can have constructors and...
3
by: GAURAV AGRAWAL | last post by:
Hi Guys, Can someone please explain me why this is happening #include<iostream> using namespace std; class a { public: int a1; // If I remove this it'll work fine
5
by: Peter | last post by:
Hi I have a class which implements IDisposable, but it doesn't really use the Dispose method for cleaning up resources, it uses it for completing a calculation. Actually I think it seems...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.