C++ Class with Static Function

Static Functions in C++ Classes can be called without creating objects of the C++ class. Creating Objects occupies memory and software developers often create static functions in C++ classes which do not access non static member variables or functions of the class. Without much technical stuff, let’s get started and create a class containing a static function. Yes there are many reasons to create static functions and this website will provide many more reasons to create static functions.

C++ Class with Static Function

C++ Class with Static Function

The sample C++ Project described in this post has a single class and a single static function in the C++ class created. Note the use of static keyword before the function body in the C++ class create. Also note that the main function does not creates object of the C++ class and instead uses the :: operator to call the public static function of the class.The public keyword allows the main function to call the function defined in the class and static keyword allows the main function to call the C++ function without creating an object.

#include "stdafx.h"#include <iostream>class CStaticFunctions{public:static void SayHello(){std::cout << "Hello From Static Function of the C++ Classn";}};int _tmain(int argc, _TCHAR* argv[]){CStaticFunctions::SayHello();return 0;}

You can copy the above code snipplet or create your own C++ Project as described in the C++ Hello World Project in this website.Once you have build your C++ project, you can run it from within Microsoft Visual Studio by pressing Ctrl + F5 keyboard shortcut and watch the output as displayed below.

Output of C++ Project Containing a Class with Static Function

Output of C++ Project Containing a Class with Static Function

Note the text displayed by the static function is displayed as the output of the C++ project. Yes the usage of static keyword requires you to understand when and why it is needed. Yes there is lots more to learn about C++, but in case you do understand simple sample projects described on this website, you are making good progress and remember C++ is the easiest programming language to learn.