C++ Programming - Constructors and Destructors - Discussion
Discussion Forum : Constructors and Destructors - Programs (Q.No. 5)
5.
What will be the output of the following program?
#include<iostream.h>
int val = 0;
class IndiaBix
{
public:
IndiaBix()
{
cout<< ++val;
}
~IndiaBix()
{
cout<< val--;
}
};
int main()
{
IndiaBix objBix1, objBix2, objBix3;
{
IndiaBix objBix4;
}
return 0;
}
Discussion:
12 comments Page 1 of 2.
Swapnil Mane said:
5 years ago
First, all objects will call to constructor we get 1234.
Then all objects will call destructor we get 4321
So the answer is =12344321.
Then all objects will call destructor we get 4321
So the answer is =12344321.
(1)
Roshni said:
6 years ago
Why the object objBix4 is declared within the brackets?
Chandu reddy said:
6 years ago
Why the objBixx4 is declared in scope and Any special is there?
Azad Rahul said:
6 years ago
The reason is that, objBix4 has its scope with in that bracket only. We can not use objBix4 outside of the bracket in main too.
Amitai said:
7 years ago
Any reason for the objBix4 to be declared again and being in brackets?
Please tell me.
Please tell me.
Varsha said:
8 years ago
@Suchitra.
It's a post-decrement that's why it will print first n then decrement.
It's a post-decrement that's why it will print first n then decrement.
Suchitra said:
9 years ago
But it should not be like that? 12343210 because value is decrementing as the destructor has been called after coming out, Out of the scope?
Karthika said:
1 decade ago
1234 are printed, once all the constructors for the corresponding objects are called (They are called once the objects are created). But destructors are called only when they come out of scope. So 4 is printed as the scope of objBix4 ends first followed by 321 once the main block is over.
(1)
Navneet said:
1 decade ago
But when constructor increment the value by 1, then destructor also decrement the value then how can it print 12344321.
Anonumous said:
1 decade ago
It will start to print from 1 because variable initialized to zero as val = 0. Then it incremented by 1, each time constructor called, till val = 4. After that, destructor called which decremented val from 4 to 1.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers