Search code examples
c++constructordestructorexplicit-constructor

Destructor of a class implicitly defined


Consider the case of class which does not have a destructor and constructor explicitly declared by the developer. I understand that a destructor for a class will be implicitly declared in this case. Then is it true that the destructor is implicitly defined, only when an object of the class is about to be destroyed?

Is the behavior of constructor also the same as above. Is it implicitly defined only when an object of the class is created?

EDIT

class A {
  public:

};
int main() {

}

In the above code, ~A() will be implicitly declared. My question is whether it true that the definition for the destructor will be made implicitly, only if an object of the class is instantiated like

class A {
      public:

    };
    int main() {
      A a;
    }

Or is it implicitly defined, even if object instantiation is not done ?


Solution

  • Yes, implicitly declared default constructors and destructors are implicitly defined when they are used to create or destroy instances of the object. In the words of the standard (C++11):

    12.1/6: A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to create an object of its class type (1.8) or when it is explicitly defaulted after its first declaration.

    12.4/5: A destructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to destroy an object of its class type (3.7) or when it is explicitly defaulted after its first declaration.

    So they are defined in your second code snippet, which creates and destroys an object of type A, but not in the first, which doesn't.