dcn
dcn

Reputation: 4469

Advantages of classes with only static methods in C++

Even though there are no static classes in C++, coming from a Java background I use to create a helper class like Util containing only static methods. Is this considered bad style or usual practice? One alternative I see is to use C functions (no class context at all). What other alternatives are there? What are there advantages and disadvantages and under which circumstances would I use any of these.

defining bunch of static methods in c++ suggests namespacing static functions as one alternative, though I fail to see what effects the static keyword without class context has.

Upvotes: 45

Views: 45392

Answers (9)

Taylor
Taylor

Reputation: 2085

Random example I haven't seen mentioned: class methods can be made static to make compile-time guarantees that free you from worrying about a class method accessing the state of an instance. Using something like const would guarantee your method doesn’t change state, but static guarantees it doesn’t even use state at all.

For example, in a class like MyClass, you might need to make calculations that are only relevant to that class (and so using global functions is cluttery) and moreover these calculations might not require access to instance members. static can let the compiler save you from yourself accidentally relying on a shaky foundation.

#include <iostream>

class MyClass {
public:
    MyClass(int input) : m_dont_use_me(input) { };
    
    int now_you_need_to_know_state(int a_member) const {
        if( m_dont_use_me > 3){
            return 999;
        }else{
            return a_member;
        }
    }
    
    static int calculate_thing(int a_member) {
        return a_member;
    }
private:
    int m_dont_use_me;


};

int main() {
    
    MyClass thing(4);
    std::cout << MyClass::calculate_thing(3) << "\n";
    std::cout << thing.now_you_need_to_know_state(3) << "\n";
    return 0;
}

Upvotes: 0

dc42
dc42

Reputation: 334

There is one other situation in which a static class might be preferred to a namespace: when you want to make the data private so that it can't be directly modified from outside the class/namespace, but for performance reasons you want to have have public inline functions that operate on it. I don't think there is any way to do that with a namespace, other than by declaring a class inside the namespace.

Upvotes: 1

James O&#39;Doherty
James O&#39;Doherty

Reputation: 2246

If you want to create a collection of utility functions without clobbering the global namespace, you should just create regular functions in their own namespace:

namespace utility {
    int helper1();
    void helper2();
};

You probably don't want to make them static functions either. Within the context of a non-member function (as opposed to a member function), the static keyword in C and C++ simply limits the scope of the function to the current source file (that is, it sort of makes the function private to the current file). It's usually only used to implement internal helper functions used by library code written in C, so that the resulting helper functions don't have symbols that are exposed to other programs. This is important for preventing clashes between names, since C doesn't have namespaces.

Upvotes: 51

Darren Engwirda
Darren Engwirda

Reputation: 7015

As many others have pointed out, free functions inside a namespace is an approach that's often taken for this sort of thing in c++.

One case I'd make for classes with all static functions is when you'd like to expose a set of functions to information derived from template parameters, i.e.

template <typename Ty>
    class utils
{
public :
// if you need to setup a bunch of secondary types, based on "Ty" that will be used 
// by your utility functions
    struct item_type
    { 
        Ty data;
        // etc
    }; 

// a set of utilities
    static void foo(Ty &data1, item_type &item)
    { 
        // etc
    }
};

You can use this to achieve the effect of a template'd namespace:

int main ()
{
    double data;
    utils<double>::item_type item ;
    utils<double>::foo(data, item);

    return 0;
}

If you're not using templates just stick with namespaces.

Hope this helps.

Upvotes: 8

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361762

In C++, classes with only static methods is mostly used in template metaprogramming.

For example, I want to calculate fibonacci numbers at compile-time itself, and at runtime I want them to print only, then I can write this program:

#include <iostream>

template<int N>
struct Fibonacci 
{
   static const int value = Fibonacci<N-1>::value + Fibonacci<N-2>::value;
   static void print()
   {
       Fibonacci<N-1>::print();
       std::cout << value << std::endl;
   }
};


template<>
struct Fibonacci<0>
{
   static const int value = 0;
   static void print()
   {
       std::cout << value << std::endl;
   }
};

template<>
struct Fibonacci<1>
{
   static const int value = 1;
   static void print()
   {
       Fibonacci<0>::print();
       std::cout << value << std::endl; 
   }
};

int main() {
        Fibonacci<20>::print(); //print first 20 finonacci numbers
        return 0;
}

Online demo : http://www.ideone.com/oH79u

Upvotes: 18

Puppy
Puppy

Reputation: 147036

In C++, just make them free functions. There's no need or reason to place them in a class at all. Unless you're doing shizzle with templates.

Upvotes: 2

EddieBytes
EddieBytes

Reputation: 1343

There is no real issue with declaring static methods within a class. Although namespaces are more suitable for this purpose for the reasons mentioned in the post you are referring to.

Using C functions can generate name collisions, unless you decide on a naming convention, prefixing your functions with stuff, for example btFunctionA, btFunctionB etc. You will want to keep your symbols within namespaces to avoid that, you are using C++ and not C after all.

Static functions within a namespace aren't any different from non-static. I believe the static keyword is simply ignored in this context.

Upvotes: 2

Tony The Lion
Tony The Lion

Reputation: 63310

C++ is a multi paradigm language, so if you need some util functions that perhaps don't really fit in a class at all, then I would just make them free functions. I don't see a reason to put them into a class, just for OOP's sake.

There is no advantage that I can see to making all functions static and putting them in a class, over having them just as free functions. Personally, I think free functions are then an easier to work with option.

Upvotes: 11

Matt
Matt

Reputation: 3848

This may be relevant to your interests. It is an article that, uh, examines the different approaches to classes and functions in Java compared to other languages.

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html

Upvotes: 1

Related Questions