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

This section contains the C++ find output programs with their explanations on C++ Static Variables and Functions (set 5).
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++;
    }
    static void fun()
    {
        cout << A << endl;
    }
};
int Sample::A = 0;

int main()
{
    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 member.

In the main() function, here we created the function pointer that is initialized with static member function of class, there is no need to mention static keyword with a function pointer. And, we created two objects S1 and S2 then we called static member function fun(). Then it will print 2 on the console screen.

Program 2:

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

class Sample {
public:
    static void fun1()
    {
        cout << "Hello ";
    }
    static void fun2()
    {
        cout << "Hiii ";
    }
};

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

    Sample S1, S2;

    F_PTR = Sample::fun1;
    F_PTR();

    F_PTR = Sample::fun2;
    F_PTR();

    return 0;
}

Output:

Hello Hiii

Explanation:

Here, we created a class Sample and two static member functions fun1() and fun2(). And, in the main() function, we created a function pointer that points fun1() and fun2() and called both functions. Then they will print "Hello Hiii" on the console screen.

Program 3:

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

static class Sample {
public:
    static void fun1()
    {
        cout << "Hello ";
    }
    static void fun2()
    {
        cout << "Hiii ";
    }
};

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

    Sample S1, S2;

    F_PTR = Sample::fun1;
    F_PTR();

    F_PTR = Sample::fun2;
    F_PTR();

    return 0;
}

Output:

main.cpp:5:1: error: a storage class can only be 
specified for objects and functions
 static class Sample {
 ^~~~~~

Explanation:

It will generate an error because we can only use static storage class with objects and functions.






Comments and Discussions!

Load comments ↻






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