What is wrong with this c++ code using destruction?

126 views Asked by At
#include <iostream.h>
class a {
public:
    ~a() { cout << 1; }
};
int main()
{
    a ob;
    ob.~a();
    return 0;
}


if wrong than what is wrong with it?
I've tried this code running on turbo c++,still i'm getting the error of

member identifier expected at "ob.~a();"line


else guess the output?

2

There are 2 answers

1
πάντα ῥεῖ On BEST ANSWER

You don't call destructor functions explicitly usually. They will be called implicitly when the instance goes out of scope.

Calling a destructor function for the same instance twice leads to undefined behavior.


There's no compiler error with a modern compiler to be observed though. See here please. May be that was one of the rare good decisions from the Turbo C++ designers leaving such in an error message.


There are rare cases to call the destructor function explicitly, e.g. if you're maintaining a pool of instances created with placement new.

0
EmDroid On

The call might work with ob.a::~a().

That being said, you don't need and should not call the destructor explicitly, it is called automatically once the ob object goes out of scope.