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

This section contains the C++ find output programs with their explanations on C++ Static Variables and Functions (set 4).
Submitted by Nidhi, on July 01, 2020

Program 1:

#include <iostream>
#include <stdlib.h>
using namespace std;

class Sample {
public:
    int B;
    static int A;
    Sample()
    {
        B = 10;
        A++;
    }
};
int Sample::A = 0;

int main()
{
    Sample S1, S2;
    new Sample();

    cout << (new Sample())->B << " ";
    cout << Sample::A;

    return 0;
}

Output:

3

Explanation:

Here, we created a class Sample that contains static data member A, non-static member B, and one default constructor. Here, we increased the value of the static member in the defined constructor.

In the main() function, we created two object S1, S2, and also create an object using a new Sample().

Look to the cout statement,

cout<<(new Sample())->B<<" "<<Sample::A;

Here, a new Sample() will return a pointer, so we directly called B using the referential operator "->" and access the value of B initialized in the constructor.

Program 2:

#include <iostream>
#include <stdlib.h>
using namespace std;

class Sample {
    int A;

public:
    Sample()
    {
        A++;
    }
    static void fun()
    {
        A++;
    }
};
int Sample::A = 0;

int main()
{
    Sample::fun();

    return 0;
}

Output:

main.cpp: In static member function ‘static void Sample::fun()’:
main.cpp:15:9: error: invalid use of member ‘Sample::A’ in static member function
         A++;
         ^
main.cpp:6:9: note: declared here
     int A;
         ^
main.cpp: At global scope:
main.cpp:18:13: error: ‘int Sample::A’ is not a static data member of ‘class Sample’
 int Sample::A = 0;
             ^

Explanation:

Here, it will generate an error because we cannot access non-static data member A in static member function fun(). A non-static member function can access static data members because static data members can be shared among all objects.

Program 3:

#include <iostream>
#include <stdlib.h>
using namespace std;

class Sample {
    static int A;

public:
    Sample()
    {
        A++;
    }
    static void fun()
    {
        cout << A << endl;
    }
};
int Sample::A = 0;

int main()
{
    static void (*F_PTR)();

    Sample S1, S2;

    F_PTR = Sample::fun;
    F_PTR();

    return 0;
}

Output:

2

Explanation:

Here, we created a class Sample that contains a static data member A, constructor, and one static data member.

In the main() function, here we created the static function pointer that is initialized with static member function of class and created two objects that will call the constructor and increase the value of A. And then we called static member function fun(). Then it will print 2 on the console screen.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.