C++ Programming - Constructors and Destructors - Discussion

Discussion Forum : Constructors and Destructors - Programs (Q.No. 9)
9.
What will be the output of the following program?
#include<iostream.h> 
class IndiaBix
{
    int x, y; 
    public:
    IndiaBix(int xx)
    {
        x = ++xx;
    } 
    ~IndiaBix()
    {
        cout<< x - 1 << " ";
    }
    void Display()
    {
        cout<< --x + 1 << " ";
    } 
};
int main()
{
    IndiaBix objBix(5);
    objBix.Display();
    int *p = (int*) &objBix;
    *p = 40;
    objBix.Display();
    return 0; 
}
6 6 4
6 6 5
5 40 38
6 40 38
6 40 39
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
17 comments Page 2 of 2.

Rajireddy-ou said:   1 decade ago
x is part of the obj. ptr is pointing to that obj. Internally *p = x.

Bittoo said:   1 decade ago
When *p=40, how could x value modifies to 40? can anybody explain this?

Shilpi said:   1 decade ago
First the value of x is 6.

After that *p=40.

So when another display is called the value print as 40.

After that destructor decreases the pointer by 2. By its size so the value becomes 38.

Komal said:   1 decade ago
First the construtor is called with arg 5 resulting in value 6.
later the objects address is assigned to pointer p that changes the value to 40finally the display() gives 39.

Tushar said:   1 decade ago
@Nadreen
I think in constructor x=41 in display it becomes again 41 cause all are predecrement so how we get 38

Nadreen said:   1 decade ago
I got it, at first the value of x was 6(++5) but it was changed to 40 by the pointer *p,then it was changed again to 39 by the function display(--x)

Nadreen said:   1 decade ago
Please explain.


Post your comments here:

Your comments will be displayed after verification.