Constructors and Destructors - Programming

Q1:

What will be the output of the following program?
#include<iostream.h> 
class AptitudeCrack
{
    int x, y; 
    public:
    AptitudeCrack(int xx)
    {
        x = ++xx;
    } 
    ~AptitudeCrack()
    {
        cout<< x - 1 << ' ';
    }
    void Display()
    {
        cout<< --x + 1 << ' ';
    } 
};
int main()
{
    AptitudeCrack objAptitude(5);
    objAptitude.Display();
    int *p = (int*) &objAptitude;
    *p = 40;
    objAptitude.Display();
    return 0; 
}

A 6 6 4

B 6 6 5

C 5 40 38

D 6 40 38

E 6 40 39

ANS:D - 6 40 38

#include<iostream>
#include<stdio.h>
using namespace std;
class AptitudeCrack
{
int x, y;
public:
AptitudeCrack(int xx)
{
x = ++xx;
cout<<"A:"<<x<<endl;
}
~AptitudeCrack()
{
cout<<"B:"<< x << endl;
}
void Display()
{
cout<<"C:"<< --x << endl;
}
};

int main()
{
AptitudeCrack objAptitude(5);
//cout<<"a"<<endl;
objAptitude.Display();
//cout<<"b"<<endl;

int *p = (int*) &objAptitude;
*p = 40;
cout<<"c"<<endl;
objAptitude.Display();
return 0;
}


AptitudeCrack objAptitude(5); // creates objects and calls the constructor so (++5) = 6
objAptitude.Display();
int *p = (int*) &objAptitude; // doesn't call the constructor instead go to the location of object where x is Changed the value of x. X = 40 now instead of 6.
*p = 40;
objAptitude.Display(); // at display --40 = 39. X value changed to 39 since we have reached the termination of the program Now deconstructor will be called X is still 39.