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;
}
Discussion:
17 comments Page 1 of 2.
Shanu said:
1 decade ago
Can anybody explain it.
Nadreen said:
1 decade ago
Please explain.
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)
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.
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
I think in constructor x=41 in display it becomes again 41 cause all are predecrement so how we get 38
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.
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.
Bittoo said:
1 decade ago
When *p=40, how could x value modifies to 40? can anybody explain this?
Rajireddy-ou said:
1 decade ago
x is part of the obj. ptr is pointing to that obj. Internally *p = x.
Shreyas said:
1 decade ago
It will print 38, because as in display(), --x + 1, ==> 39+1;
As now the x contains 39 not 40, so when destructor is called i.e x - 1 ==> 39-1 = 38.
As now the x contains 39 not 40, so when destructor is called i.e x - 1 ==> 39-1 = 38.
Ghulam Mustafa said:
9 years ago
Anyone can Explain more precise?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers