C++ Programming - Constructors and Destructors - Discussion

Discussion :: Constructors and Destructors - Programs (Q.No.5)


What will be the output of the following program?

int val = 0; 
class IndiaBix
        cout<< ++val;
        cout<< val--; 
int main()
    IndiaBix objBix1, objBix2, objBix3;
        IndiaBix objBix4;
    return 0;

[A]. 1234
[B]. 4321
[C]. 12344321
[D]. 12341234
[E]. 43211234

Answer: Option C


No answer description available for this question.

Jyoti said: (Oct 17, 2012)  
When objects are created constructor is called again and again but destructor destroys the object in reverse order.

Sowjanya said: (Aug 24, 2013)  
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?

Anonumous said: (Sep 9, 2013)  
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: (Oct 4, 2013)  
But when constructor increment the value by 1, then destructor also decrement the value then how can it print 12344321.

Karthika said: (Jul 30, 2014)  
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.

Suchitra said: (Dec 4, 2016)  
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: (Sep 26, 2017)  

It's a post-decrement that's why it will print first n then decrement.

Amitai said: (Dec 4, 2018)  
Any reason for the objBix4 to be declared again and being in brackets?

Please tell me.

Azad Rahul said: (Jul 20, 2019)  
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: (Dec 19, 2019)  
Why the objBixx4 is declared in scope and Any special is there?

Roshni said: (Jan 11, 2020)  
Why the object objBix4 is declared within the brackets?

Swapnil Mane said: (Jun 10, 2020)  
First, all objects will call to constructor we get 1234.
Then all objects will call destructor we get 4321
So the answer is =12344321.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.