Hello,
I have such code and I don't know where the second A.f in output comes from. I suppose the first is from new A(), but don't have a clue about the second.
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
*Note: If your destructor is virtual and therefore can be overidden, calling delete a; will also call the B's dtor and then A's dtor.
NOTE: Your program can have undefined behavior.
In function 'int main()':
41:12: warning: deleting object of polymorphic class type 'A' which has non-virtual destructor might cause undefined behaviour [-Wdelete-non-virtual-dtor]
To fix this, you need to mark your A class as having a virtual destructor
First, new A() calls f(). This is the first A.f.
Then, new B() implicitly calls the default constructor for A() as its being created, since B is a subclass of a A. This is the second A.f.
The base class is always constructed before the subclass.
Also, here's an example showing differences in behavior when the destructor is virtual: