What are Destructors

beginner c++11 classes

Related: Classes

C++ has a deterministic method of releasing resources, called destructors. Destructors are special functions that share their class’s name but always start with a tilde (~). While classes and structs can have multiple constructors, each can only have one destructor. Whenever an object goes out of scope (the end of a scope is marked with }) its destructor is called automatically. C++ does this for all types and variables in your program, right when their owning scope ends. Destructors are usually invisible, dutifully running when an object goes out of scope. Here’s an example that emphasises destructors:

#include <iostream>
#include <vector>

class Talker {
public:
  explicit Talker(std::string name) : name_(std::move(name)) {
    std::cout << name_ << " here.\n";
  }
  ~Talker() {
    std::cout <<  name_ << ", signing off.\n";
  }
private:
  std::string name_;
};

int main() {
  Talker johnny("Maria");
  {
    std::vector<Talker> vec; 
    vec.emplace_back("Nushi");
  }
  Talker jose("Jose");
}
Maria here.
Nushi here.
Nushi, signing off.
Jose here.
Jose, signing off.
Maria, signing off.


For more C++ By Example, click here.