3

Consider this example :

#include <iostream>
using namespace std;

class MyClass
{
public:
    ~MyClass() { cout << "DTOR OK !" << endl; }
};

int main(void)
{
    MyClass test();
    MyClass* pTest = new MyClass();
    delete pTest;
}

Why "DTOR OK !" is not printed twice ? why the destructor of the local object "test" is not called ?

When the destructor is private, I've noticed that there is only a compile error for delete pTest; but not for the local object ? what's happening here ?

Aminos
  • 754
  • 1
  • 20
  • 40

2 Answers2

7

This line actually declares a function, not a variable.

MyClass test();

If you were to change to uniform initialization syntax, you'd see two destuctor calls

MyClass test{};

or

auto test = MyClass();
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    For completeness, this is called the "Most Vexing Parse." Might be good to note that so that the OP can search it later on. :-) – templatetypedef Feb 13 '17 at 18:41
  • 3
    @templatetypedef This is not the most vexing parse – NathanOliver Feb 13 '17 at 18:42
  • OK, I thought that we can't put function prototypes inside main(), but apparently we can't only put the implementation... – Aminos Feb 13 '17 at 18:57
  • 1
    @Aminos *OK, I thought that we can't put function prototypes inside main()* -- FYI, this has existed since good old `C`. – PaulMcKenzie Feb 13 '17 at 19:19
  • @NathanOliver I was under the impression that the Most Vexing Parse was the general term for "a statement that looks like a variable declaration but actually is a function declaration." Is that incorrect? I'm happy to be corrected! – templatetypedef Feb 13 '17 at 21:56
2

"MyClass test();" - you wanted to write MyClass test; - you are not creating an object, you are declaring a function "test" that takes no arguments and returns a "MyClass".

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70