Cpp code on Destructor?

All QuestionsCategory: Cpp LanguageCpp code on Destructor?
Anonymous asked 3 years ago
1 Answers
Anonymous answered 3 years ago

About Destructor
 

  • Same name as class name prefixed by ~
  • No parameters, No return types
  • Use to deinitialize object state
    • By releasing any external resources
    • Reversing of any explicit initialization inside the constructor
  • Invoked just before the object is going out of scope (object’s memory is getting destroyed)
  • In absence of user provided destructor, compiler provides an implicit one, which is blank (does nothing)

 
Example
 

class Box {
private:
  int length;
  int breadth;
  int height;

public:
  Box(int x, int y, int z):length(x),breadth(y),height(z) { }
  Box():length(0),breadth(0),height(0) { }
  ~Box() {
    std::cout << "Box class destructor" << "\n";
  }
  int Box::getVolume() const { return length * breadth * height; }
  void Box::display() const {
    //print length, breadth, height
  }
};
int main() {

  Box b1(10, 12, 5);
  std::cout << b1.getVolume() << "\n";

  Box *pb = new Box(1, 8, 6);

  Box b2;
  Box b3(b1);
  delete pb;

  return 0;
}


ou Should Know - Myths and Facts


Constructor is not meant for allocating memory for the object (own members) and the destructor is not for releasing object’s own memory. Object memory is managed by lifetime rules as per scope (local, global, heap).