7

Is there any difference between

class C { static int func(); }; 

and

class C { int static func(); }; 

I'm trying to remove the keyword static in someone else's code base. And I want to make sure I understand what the second example means before I do that.

[Edit] The reason to remove static: C was a "class" with no member variables and full of static methods. I think it's more proper to make "C" a namespace with normal functions instead of a class.

8
  • 2
    Why are you trying to remove it? Commented Apr 19, 2013 at 14:22
  • 1
    Because C was a "class" with no member variables and full of static methods. I think it's more proper to make "C" a namespace instead of a class. Am I right? Commented Apr 19, 2013 at 14:26
  • That's indeed the idiomatic C++ approach. The original coder might have been a Java developer (they don't have namespace). Commented Apr 19, 2013 at 14:32
  • 3
    @user2207811: You can find people that will fall both ways. Using a class forces qualification of the functions that are called, and avoids potential conflicts with unqualified functions. Commented Apr 19, 2013 at 14:43
  • 4
    @DavidRodríguez-dribeas: and let's not forget that a class can be used as a template parameter, whilst a namespace cannot. Commented Apr 19, 2013 at 14:48

2 Answers 2

10

There is no difference. static on the function declaration applies to the function.
An this pointer will not be implicitly passed to this function, So you cannot access non static class members inside this function without explicitly passing the object to it.

To remove the static first you should know and understand the purpose that it is designed this way. Without taking that in to consideration you are just bound to create a code smell of vast proportions.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there any difference between static int i vs int static i?
Please see my comment under the question. I think I'm doing the right thing
@RasmiRanjanNayak: None, apart from confusing the one who will maintain it.
@user2207811: If you have a class with no data members and only static functions you are much better off using an Unnamed namespace
@Alok: No, an unnamed namespace is a terrible solution. A class is accessible from multiple compilation units. So is a named namespace.
|
3

Yes, in the first case, the keyword static comes before the type int, in the second, they are the other way around. However, like many things in C and C++, there is no semantic difference. So, other than "cosmetically", there is no difference.

I'm not sure why you would want to remove static in classes as a general rule - there is probably a good reason a member function is declared static.

1 Comment

So your answer to "Is there a difference?" is "Yes."?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.