Q:

C++ Static Variables and Functions | Find output programs | Set 3

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Static Variables and Functions (set 3).

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;
}

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;
}

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

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.

Answer Program 2:

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.

Answer Program 3:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Static Variables and Functions | Find output p... >>
<< C++ Static Variables and Functions | Find output p...