Constructor and Destructor
Constructor
  1. //Rectangle.h
  2. #ifndef RECTANGLE_H
  3. #define RECTANGLE_H
  4. class Rectangle
  5. {
  6. private:
  7. double width;
  8. double length;
  9. public:
  10. //constructor
  11. Rectangle(double w, double l);
  12.  
  13. //accessor
  14. double getWidth() const;
  15. double getLength() const;
  16. double getArea() const;
  17.  
  18. //mutator
  19. void setWidth(double w);
  20. void setLength(double l);
  21. };
  22. #endif
  1. //Rectangle.cpp
  2. #include "Rectangle.h"
  3.  
  4. Rectangle::Rectangle(double w, double l):width(w), length(l){}
  5.  
  6. double Rectangle::getWidth() const
  7. {
  8. return width;
  9. }
  10.  
  11. double Rectangle::getLength() const
  12. {
  13. return length;
  14. }
  15.  
  16. double Rectangle::getArea() const
  17. {
  18. return width*length;
  19. }
  20.  
  21. void Rectangle::setWidth(double w)
  22. {
  23. width = w;
  24. }
  25.  
  26. void Rectangle::setLength(double l)
  27. {
  28. length = l;
  29. }
  1. //main.cpp
  2. #include <iostream>
  3. #include "Rectangle.h"
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. Rectangle *r;
  8. r = new Rectangle(5, 10);
  9.  
  10. std::cout<<"Area: "<<r->getArea()<<std::endl;
  11.  
  12. return 0;
  13. }
Destructor
  1. //V.h
  2. #ifndef V_H
  3. #define V_H
  4. class V
  5. {
  6. private:
  7. int size;
  8. double *array;
  9. public:
  10. V(int s);
  11. V(double *a, int s);
  12. int getSize() const;
  13. double *getArray() const;
  14. void display() const;
  15. ~V();
  16. };
  17. #endif
  18.  
  19. //V.cpp
  20. #include <cstdlib>
  21. #include <iostream>
  22. #include "V.h"
  23. V::V(int s)
  24. {
  25. std::cout<<"Constructor V(s) ..."<<std::endl;
  26. size = s;
  27. array = new double[size];
  28. for(int i = 0; i < size; i++)
  29. array[i] = rand()%100;
  30. }
  31.  
  32. V::V(double *a, int s)
  33. {
  34. std::cout<<"Constructor V(a, s) ..."<<std::endl;
  35. size = s;
  36. array = a;
  37. }
  38.  
  39. int V::getSize() const
  40. {
  41. return size;
  42. }
  43.  
  44. double *V::getArray() const
  45. {
  46. return array;
  47. }
  48.  
  49. void V::display() const
  50. {
  51. for(int i = 0; i < size; i++)
  52. std::cout<<array[i]<<" ";
  53. std::cout<<std::endl;
  54. }
  55. V::~V()
  56. {
  57. std::cout<<"Destructor "<<size<<" ..."<<std::endl;
  58. size = 0;
  59. delete [] array;
  60. //array = 0;
  61. }
  62.  
  63. //main.cpp
  64. #include <iostream>
  65. #include <cstdlib>
  66. #include "V.h"
  67.  
  68. int main(int argc, char *argv[])
  69. {
  70. V v(5);
  71. v.display();
  72.  
  73. V *v2 = new V(10);
  74. v2->display();
  75. delete v2;
  76.  
  77. double *array = new double [15];
  78. for(int i = 0; i < 15; i++)
  79. array[i] = rand()%100;
  80. V *v3 = new V(array, 15);
  81. v3->display();
  82. delete v3;
  83.  
  84. return 0;
  85. }