Home »
C++ programming »
C++ find output programs
C++ Static Variables and Functions | Find output programs | Set 3
This section contains the C++ find output programs with their explanations on C++ Static Variables and Functions (set 3).
Submitted by Nidhi, on July 01, 2020
Program 1:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
static int A;
public:
Sample()
{
A++;
}
};
int Sample::A = 0;
int main()
{
Sample S1, S2, *S3;
S3 = (Sample*)malloc(sizeof(Sample));
cout << Sample::A;
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:21:21: error: ‘int Sample::A’ is private within this context
cout << Sample::A;
^
main.cpp:14:5: note: declared private here
int Sample::A = 0;
^~~~~~
Explanation:
In this program, we are trying to access the private data member outside the class and cannot access private data members outside the class.
Program 2:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
public:
static int A;
Sample()
{
A++;
}
};
int Sample::A = 0;
int main()
{
Sample S1, S2, *S3;
S3 = (Sample*)malloc(sizeof(Sample));
cout << Sample::A;
return 0;
}
Output:
2
Explanation:
Here, we created a class Sample that contains one static data member and one default constructor. Here, we increased the value of the static member in the defined constructor.
In the main() function, here we created two objects S1 and S2 and created one pointer S3, that initialized using malloc() function. But the constructor will call for S1 and S2, but the constructor will not call when we use malloc() function, then the final value of A will be 2.
Program 3:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
public:
static int A;
Sample()
{
A++;
}
};
int Sample::A = 0;
int main()
{
Sample S1, S2;
new Sample();
cout << Sample::A;
return 0;
}
Output:
3
Explanation:
Here, we created a class Sample that contains one static data member and one default constructor. Here, we increased the value of the static member in the defined constructor.
In the main() function, here we created two object S1, S2, and also created an object using a new Sample().
So, here constructor will call 3 times, then "3" will be printed on the console screen.