Can you tell me whats the output here and explain to me how!!

int volume = 0;
Class Box
{
Box ()
{
Cout<<++volume;
}
~Box()
{
Cout<<volume--;
}
};
Void main (){
Box object1,object2,object3;
{
Box object4;
}
}
closed account (o3hC5Di1)
Hi there,

Please wrap your code in between [code][/code]-tags.
Here's your corrected code with the output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int volume = 0;
class Box
{
    public:
        Box ()
        {
            std::cout<<++volume;
        }
        ~Box()
        {
        std::cout<<volume--;
        }
};

int main ()
{
    Box object1,object2,object3;
    {
        Box object4;
    }
}
12344321


Box() is a constructor, which means it is automatically called upon the creation of an object. ~Box() is a destructor, which is automatically called when an object is destroyed, either by delete or when it goes out of scope. This bit of your code is a good example:

1
2
3
{ //anonymous code block (scope)
        Box object4; //object created, constructor called
    }// object scope ends, destructor is called 


Hope that helps.

All the best,
NwN
Why don't you simply compile and run the program yourself?

Your main() creates four local objects. Constructors are executed on creation. Destruction is executed when local objects exit scope, so at end of main().

Pre-increment first increments and then returns the new value. Post-increment increments too, but the return value is the original value.

C++ is case sensitive.
Topic archived. No new replies allowed.