Open In App
Related Articles

C++ | Static Keyword | Question 6

Improve Article
Improve
Save Article
Save
Like Article
Like

Output of following C++ program?




#include <iostream>
class Test
{
public:
    void fun();
};
static void Test::fun()   
{
    std::cout<<"fun() is static\n";
}
int main()
{
    Test::fun();   
    return 0;
}


Contributed by Pravasi Meet
(A) fun() is static
(B) Empty Screen
(C) Compiler Error


Answer: (C)

Explanation: The above program fails in compilation and shows below error messages.
[Error] cannot declare member function ‘void Test::fun()’ to have static linkage [-fpermissive]
In function ‘int main()’:
[Error] cannot call member function ‘void Test::fun()’ without object

If the static function is to be defined outside the class then static keyword must be present in function declaration only not in the definition outside the class.

Following program is now correct.




#include <iostream>
class Test
{
public:
    static void fun();
};
void Test::fun()
{
    std::cout<<"fun() is static\n";
}
int main()
{
    Test::fun();
    return 0;
}



Quiz of this Question

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads