Where have you used static functions in C++ project?

Answer: Real time situations where we use static member functions in C++.

Note: For this interview question, you should find the specific scenarios in your project where you have used c++ static functions. If you have not used, you can answer general scenario where we can use static functions in a c++ project.

Singleton class

We know that this class itself creates and returns single object using a static function in C++ and does not allow users to create objects from outside of the class.

As, we cannot create object from outside of the singleton class we cannot call any instance method using an object. So, we have only option to make function static , so, we can call it by class name and scope resolution operator to get a singleton class object.

Recommended: Singleton class in C++.

Utility Class:

Many times we get a requirement to write utilities functions in C++ projects, for example, File logging and algorithms i.e. sorting, reverse and searching etc. and user class does not have to do anything with utility class’s data members or utility class doesn’t have any data members at all and it contains functions only. Then we create a utility class and keep collection of utilities functions into it. For example

class Utils
{
private:
      //make the Utils class constructor private to dis-allow object creation from
      // outside of this class. User class will use only class name to call it's functions.
	Utils();t
public:
	static void utilone(){
		//do something
	}
	static void utiltwo(){
		//do something
	}
};

In this case, creating object of the class is redundant and waste of memory (performance issue). Hence, we make all utilities functions static and invoke them by class name. And also, we make constructors private to dis-allow creation of object from outside of class as a good practice.

NOTES:

  • During writing of a class whenever you think object creation is not required, make the constructor private and make all c++ functions static as a best practice.
  • Utility class is not a concept but just we create our own utility class and keep collection of utilities functions into it. E.g. “class StringUtility and “class Filelogging” etc.

Related Posts