Question

I'm trying to call the destructor of a class explicitly in Turbo C++:

A a;
a.~A();

But it's showing an error:

Member identifier expected.

Is there any way to explicitly call a destructor in Turbo C++?

Was it helpful?

Solution

From this link, it seems you actually can do it, the valid format is:

A a;
// a.~A(); // Wrong - Member identifier expected
a.A::~A(); // Valid

But I don't have a Turbo C++ compiler handy to test it, so you'll have to test it.

[Edit]

OP tested it, it works.

OTHER TIPS

You don't need to call destructor explicitly, when an object with automatic duration goes out of scope, its destructor will be called implicitly.

void main()
{
    A a;
    //a.~A();  // you need to comment out this line
} // a.~A() is called again, you try to destroy an object twice.

While @billz is right that you don't have to call it explicitly, the line itself should be valid. A destructor is a regular method and can be called like that. This can be useful if you implement your own operator new and operator delete but in your case, just stick with billz answer.

The problem which leads to an error message seems to be that you have a too-old compiler, as evidenced by <iostream.h> or void main(). Fixing the old-school-stuff (but not the a.~A();) the code compiles with GCC 4.8.

As per your requirement, following code works well

 #include <iostream>

 class A
 {
    public:
     A() { }
     ~A() { std::cout<<"\n ~A()"; }
 };

 int main()
 {

      A a;
      a.A::~A();
      return 0;
  }

But beware of Calling the D'tor explicitly. Because compiler will insert the code for an auto obejcts that are inside the function. In the above code will result in calling the D'tor twice i.e

 int main()
 {
   A a;
   a.A::~(); //which we provided
   a.A::~(); // provided by the compiler for auto objects
   return 0;
 }

We have to explicitly call the D'tor only for the placment new operator here for more details.

If the compiler doesn't allow the standard syntax for an explicit destructor call, then it probably doesn't allow you to do that.

Your compiler is about twenty years old, and the language has been through at least two major revisions since then. I don't have enough historical knowledge (or interest) to know whether its dialect is supposed to allow explicit destruction; but if you want to write modern(ish) C++ then you'll need a modern(ish) compiler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top