-1
class Test
{
public:
    Test() { cout << "Constructor is executed\n"; }  
    ~Test() { cout << "Destructor is executed\n"; }
    friend void fun(Test t);
};
void fun(Test t)
{
    Test();
    t.~Test();
}
int main()
{
    Test();
    Test t;
    fun(t);
     return 0;
}

Output I got for the code is as follows:

 **Constructor is executed**   //This is when Test() is called
 **Destructor is executed**    //This is when Test() is called
 **Constructor is executed**   //This is when Test t is called
 //In the fun function
 **Constructor is executed**   //This is when Test() is called
 **Destructor is executed**   //This is when Test() is called
 **Destructor is executed**   //This is when t.~Test() is called
 **Destructor is executed**   // Don't know where this destructor comes from!
 **Destructor is executed**   //This is when Test t is called

I am not able to trace where the second last "destructor is executed" belongs to...!!!

jpo38
  • 20,821
  • 10
  • 70
  • 151
Rian Joy
  • 21
  • 2

1 Answers1

0
#include "stdafx.h"
#include <iostream>
#include <conio.h>

using std::cout;

class Test
{
public:
    Test() { cout << "Constructor is executed\n"; }  
    ~Test() { cout << "Destructor is executed\n"; }
    friend void fun(Test t);
};
void fun(Test t) // Construct new object can be displayed by adding Test(const Test& rhs) { cout << "Constructor is executed\n"; }
{
    Test();
    t.~Test(); // Destruct created object
} 

int main()
{
    Test();
    Test t;
    fun(t);
    _getch();
     return 0;
}
Mykola
  • 3,343
  • 6
  • 23
  • 39
  • so u mean to say the second last destructor called belongs to 't' of function 'fun'..??? – Rian Joy Oct 11 '15 at 11:36
  • yes it is definitely belongs to 't' of function 'fun' – Mykola Oct 11 '15 at 11:48
  • sir culd u pls xplain where is the constructor of 't' of function 'fun' called if its destructor is called at the 2nd last step? – Rian Joy Oct 11 '15 at 12:13
  • if there is no copy constructor defined in class, the compiler implicity provides it with default version which only copy all fields of current object to newone – Mykola Oct 11 '15 at 12:14
  • if you add Test(const Test& rhs) { cout << "Constructor is executed\n"; } to the class it display creation in fun(Test t) function call – Mykola Oct 11 '15 at 12:16
  • here is [cppreference](http://en.cppreference.com/w/cpp/language/copy_constructor) link – Mykola Oct 11 '15 at 12:19
  • so are u trying to say that 't' when returned by 'fun' only show destructr and doesn't show construction for it anywhere in the output!! – Rian Joy Oct 11 '15 at 13:03
  • yes, to display it must be added "Test(const Test& rhs) { cout << "Constructor is executed\n"; } ", to show function parameter construction process. – Mykola Oct 11 '15 at 13:11