C++ Programming - Objects and Classes - Discussion
Discussion Forum : Objects and Classes - Programs (Q.No. 13)
13.
Which of the following statement is correct about the program given below?
#include<iostream.h>
#include<process.h>
class IndiaBix
{
static int x;
public:
IndiaBix()
{
if(x == 1)
exit(0);
else
x++;
}
void Display()
{
cout<< x << " ";
}
};
int IndiaBix::x = 0;
int main()
{
IndiaBix objBix1;
objBix1.Display();
IndiaBix objBix2;
objBix2.Display();
return 0;
}
Discussion:
13 comments Page 1 of 2.
Sheetal said:
1 decade ago
Here when objbix1 is constructed, the condition given in constructor fn is checked. Now x=0, so ++x will be executed and x value becomes 1 and the output comes as 1 when display fn is called. But when objbix2 is constructed then since x=1 so the program exits ie terminated and nothing is displayed afterwards. So the output is 1.
K SOWJANYA said:
1 decade ago
But how, only static functions can access static variables, x is static variable but display() is not.
Sucheta said:
1 decade ago
Answer is the program will report compile time error as x is static variable which we can not use in display fun.
Somebody said:
1 decade ago
Static variables can be used inside both static and nonstatic member function directly.
Abhishek said:
1 decade ago
A static member variable can be accessed by both non-static and static member functions. Although that is not the issue here.
I think the output should be 1 1 cause obj2 is executing the display function.
I think the output should be 1 1 cause obj2 is executing the display function.
Aryan said:
1 decade ago
What is process.h even this is not work in given compiler?
Sush said:
9 years ago
Static member functions can only use a static variable and not other variables. Static variables can be used by any member functions.
Deepanshu tyagi said:
7 years ago
Constructor Cannot Access Static Variables. Static Variables Acesss By Only Static member Variable.
Hasita said:
7 years ago
How x++ becomes ++x? Please explain.
Rashmi said:
7 years ago
Here x=0 firstly,
Then constructor that is called by objBix1, x==1 is condition will be false, so x++ means x=1;
ext objBix2 calls constructor and x==1 is true, so the program will be terminated.
That's it..
Then constructor that is called by objBix1, x==1 is condition will be false, so x++ means x=1;
ext objBix2 calls constructor and x==1 is true, so the program will be terminated.
That's it..
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers