1

Is destructor called in such piece of code when a is destroyed?

extern "C" {
    int func()
    {
        A a(); // a is object of class A
    }
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380

4 Answers4

3

extern "C" is a link-time directive. It does not change how the language itself works.

No destructor is called in your case since A a(); is declaring a function prototype for a function that takes no arguments and returns an A. It does not create an instance of A. (See most vexing parse).

If you had written A a; instead, then the default constructor would have been called, along with the destructor once a goes out of scope.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

such questions can be answered at home by building a tiny test program:

#include <iostream>

struct A
{
    ~A() { std::cout << __func__ << std::endl; }
};

extern "C" {
    int func()
    {
        A a; // a is object of class A
        return 0;
    }
}

int main()
{
    func();
    return 0;
}

expected output:

~A

Answer: yes

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
2

The language linkage of the function name has no effect on the semantics of the function. It only affects how the name is seen within the program.

Your function behaves as expected. (Though your expectations may differ from what you wrote.)

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

The extern "C" qualification just affects how the function can be called and imposes some constraints on the function signature. It doesn't affect its implementation. That is, if there were an object inside your function, it would be both constructed and destroyed.

Of course, in the code in the question there is actually no object created as A a(); is a function declaration. If you want to actually create an object and invoke its default constructor, you'd use, e.g., one of the definitions below:

A a1 = A();
A a2{};
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380