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.
Jyoti said:
1 decade ago
When objects are created constructor is called again and again but destructor destroys the object in reverse order.
SOWJANYA said:
1 decade ago
Can anyone please clear my doubt?
In program we passed the value 4 how can it prints 1 first? Why it prints the value 1 first? Can anyone explain the procedure how it will?
In program we passed the value 4 how can it prints 1 first? Why it prints the value 1 first? Can anyone explain the procedure how it will?
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.
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.
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)
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?
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.
Amitai said:
7 years ago
Any reason for the objBix4 to be declared again and being in brackets?
Please tell me.
Please tell me.
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.
Chandu reddy said:
6 years ago
Why the objBixx4 is declared in scope and Any special is there?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers