the position of the *static* keyword in member method declaration - c++

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.

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.

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.

Related

How can I prevent static class member variables from needing two definitions/declarations?

I don't think this is a duplicate because other questions ask why it's necessary, not how I can avoid writing it twice.
Often with classes I'll introduce member variables and then, for whatever reason, remove them shortly after if I don't like them.
With a non-static member variable I can simply add a member to the header file and use it in my code immediately. With a static member variable I have to do the following:
Add the new member to the class definition, e.g. static int a;.
Copy the new member declaration.
Go to a .cpp file (any .cpp file will do if I understand right).
Paste the variable in the file.
Remove the static keyword.
Add the class namespace/scope after the type and before the variable name.
All of this makes me want to just make all of my classes instantiable and do everything through an object, even if it wouldn't make sense.
So even if this is just a requirement of the language and there is no way around it, is there a way to cut back on the repetition by using macros in some way?
Also I was thinking if maybe it mightn't be simpler to just have one .cpp file containing all of these static member variable definitions. Seeing as though (I've heard) static member variables are basically global variables accessed through a class namespace, is this a better idea than doing it in each corresponding .cpp file?
I'm going to provide a solution for integral types (since you highlight those types in your question):
struct Foo
{
enum {Value = 123;}
};
Value can be used as an integral constant, is the same for all instances of Foo (rather like a static) and does not require definition in a source file. Note though that &Value makes no sense, i.e. there's no such thing as a pointer to an enumeration value.
You can do things with constexpr in later C++ standards (C++11 onwards), but my way is arguably simpler and is also an important metaprogramming technique.
(If this is not sufficient for what you want then please downvote and I'll remove.)
A possibility is too use static in function scope, something like:
struct C {
static int& a() {
static int a_instance = 42;
return a_instance;
}
};

static functions compiler optimization C++

I know that we should declare a function as static in a class if its a utility function or if we have to use in a singleton class to access private static member.
But apart from that does a static function provide any sort of compiler optimization too since it doesn't pass the "this" pointer? Why not just use the utility function through an already instantiated object of class? Or is it just a best practice to make utility functions as statics?
Thanks in advance.
The "non-passing-this" optimization can probably be done by the compiler once you turn the optimizations on. As I see it, a static function has rather idiomatic uses:
Implementing modules. There is a bit of overlap here with namespaces, and I would rather use namespaces.
Factories: you can make the constructor protected/private and then have several static functions (with different, explicit names) creating instances.
For function pointers: static functions do not require the slightly more complicated syntax of pointer to member function. That can be a plus when interacting with libraries written for C.
To keep yourself from using this and have the compiler to enforce it. It makes sense sometimes. For example, if you have a commutative operation that takes two instances, a static function that takes the two instances would emphasize (in my opinion) that the operation is commutative. Of course in many cases you would rather overload an operator.
In general a static function will ease namespace and "friend" clutter by prefixing an otherwise ordinary function with the name of a class, presumably because both are tightly related.
Static exists to associate a method with a class, rather than either:
Associating it with an instance of that class (like writing a normal, non-static member function).
Keeping it in the global namespace or whatever namespace you would otherwise be in (like declaring a function just in the file, not in a class).
Static says that 'conceptually this is something tied to/associated with this class, but it does not depend on any instance of that class'.
In more formal terms: a static member function is the same as a function declared outside of a class in all ways other than that it is part of that class's namespace and in that it has access rights to that class's private/protected data members.
Going back to your question:
There is no optimization gain here.
Utility function has nothing to do with it. It's whether or not it makes sense to scope the function in the class itself (rather than an instance of it).
It does not 'pass the this pointer' because there is no instance to speak of. You can call a static member function without ever invoking that class's constructor.

Why field inside a local class cannot be static?

void foo (int x)
{
struct A { static const int d = 0; }; // error
}
Other than the reference from standard, is there any motivation behind this to disallow static field inside an inner class ?
error: field `foo(int)::A::d' in local class cannot be static
Edit: However, static member functions are allowed. I have one use case for such scenario. Suppose I want foo() to be called only for PODs then I can implement it like,
template<typename T>
void foo (T x)
{
struct A { static const T d = 0; }; // many compilers allow double, float etc.
}
foo() should pass for PODs only (if static is allowed) and not for other data types. This is just one use case which comes to my mind.
Because, static members of a class need to be defined in global a scope, e.g.
foo.h
class A {
static int dude;
};
foo.cpp
int A::dude = 314;
Since the scope inside void foo(int x) is local to that function, there is no scope to define its static member[s].
Magnus Skog has given the real answer: a static data member is just a declaration; the object must be defined elsewhere, at namespace scope, and the class definition isn't visible at namespace scope.
Note that this restriction only applies to static data members. Which means that there is a simple work-around:
class Local
{
static int& static_i()
{
static int value;
return value;
}
};
This provides you with exactly the same functionality, at the cost of
using the function syntax to access it.
Because nobody saw any need for it ?
[edit]: static variables need be defined only once, generally outside of the class (except for built-ins). Allowing them within a local class would require designing a way to define them also. [/edit]
Any feature added to a language has a cost:
it must be implemented by the compiler
it must be maintained in the compiler (and may introduce bugs, even in other features)
it lives in the compiler (and thus may cause some slow down even when unused)
Sometimes, not implementing a feature is the right decision.
Local functions, and classes, add difficulty already to the language, for little gain: they can be avoided with static functions and unnamed namespaces.
Frankly, if I had to make the decision, I'd remove them entirely: they just clutter the grammar.
A single example: The Most Vexing Parse.
I think this is the same naming problem that has prevented us from using local types in template instantiations.
The name foo()::A::d is not a good name for the linker to resolve, so how should it find the definition of the static member? What if there is another struct A in function baz()?
Interesting question, but I have difficulty understanding why you'd want a static member in a local class. Statics are typically used to maintain state across program flow, but in this case wouldn't it be better to use a static variable whose scope was foo()?
If I had to guess why the restriction exists, I'd say it was something to do with the difficulty for the compiler in knowing when to perform the static initialisation. The C++ standards docs might provide a more formal justification.
Just because.
One annoying thing about C++ is that there's a strong dependence on a "global context" concept where everything must be uniquely named. Even the nested namespaces machinery is just string trickery.
I suppose (just a wild guess) that one serious technical issue is working with linkers that were designed for C and that just got some tweak to get them working with C++ (and C++ code needs C interoperability).
It would be nice to be able to get any C++ code and "wrap it" to be able to use it without conflicts in a larger project, but this is not the case because of linkage problems. I don't think there is any reasonable philosophical reason for forbidding statics or non-inline methods (or even nested functions) at the function level but this is what we got (for now).
Even the declaration/definition duality with all its annoying verbosity and implications is just about implementation problems (and to give the ability to sell usable object code without providing the source, something that is now a lot less popular for good reasons).

Is there any reason to use this->

I am programming in C++ for many years, still I have doubt about one thing. In many places in other people code I see something like:
void Classx::memberfunction()
{
this->doSomething();
}
If I need to import/use that code, I simply remove the this-> part, and I have never seen anything broken or having some side-effects.
void Classx::memberfunction()
{
doSomething();
}
So, do you know of any reason to use such construct?
EDIT: Please note that I'm talking about member functions here, not variables. I understand it can be used when you want to make a distinction between a member variable and function parameter.
EDIT: apparent duplicate:
Are there any reasons not to use "this" ("Self", "Me", ...)?
The only place where it really makes a difference is in templates in derived classes:
template<typename T>
class A {
protected:
T x;
};
template<typename T>
class B : A<T> {
public:
T get() {
return this->x;
}
};
Due to details in the name lookup in C++ compilers, it has to be made explicitly clear that x is a (inherited) member of the class, most easily done with this->x. But this is a rather esoteric case, if you don't have templated class hierarchies you don't really need to explicitly use this to access members of a class.
If there is another variable in the same scope with the same name, the this-> will remove the ambiguity.
void Bar::setFoo(int foo)
{
this->foo = foo;
}
Also it makes it clear that you're refering to a member variable / function.
To guarantee you trigger compiler errors if there is a macro that might be defined with the same name as your member function and you're not certain if it has been reliably undefined.
No kidding, I'm pretty sure I've had to do exactly this for that reason!
As "code reason", to distinguish a local parameter or value (that takes precedence) from a member:
class Foo
{
int member;
void SetMember(int member)
{
this->member = member;
}
}
However, that's bad practive to begin with, and usually can be solved locally.
The second reason is more "environment": it sometimes helps Intellisense to filter what I am really looking for. However, I also thing when I use this to find the member I am looking for I should also remove this.
So yes, there are good reasons, but they are all temporary (and bad on the long run).
I can think of readability like when you use additional parenthesis to make things clear.
I think it is mainly as an aid to the reader. It makes it explicit that what is being called is a method on the object, and not an ordinary function. When reading code, it can be helpful to know that the called function can change fields in the current object, for instance.
It's your own choice. I find it more clear when you use this. But if you don't like it, you can ommit it.
This is done to be explicit about the fact that the variable being used is a member variable as opposed to a local or global variable. It's not necessary in most cases, but being explicit about the scope could be helpful if you've trumped the variable with a declaration of the same name in a tighter scope.
At companies I've worked at, we just prepended "m_" to member variables. It can be helpful sometimes, and I much prefer it to using "this->".
Edit:
Adding a link to the GCC docs, which explain a case where using this-> is necessary to get a non-dependent lookup to work correctly.
This is really a matter of style and applies to many other languages such as Java and C#. Some people prefer to see the explicit this (or self, or Me, or whatever) and others do not. Just go with whatever is in your style guidelines, and if it's your project, you get to decide the guidelines.
There are many good answers, but none of them mention that using this-> in source code makes it easier to read, especially when you are reading a code of some long function, but even a short function, imagine a code:
bool Class::Foo()
{
return SomeValue;
}
from looking on this code, you can't clearly know what SomeValue is. It could be even some #define, or static variable, but if you write
bool Class::Foo()
{
return this->SomeValue;
}
you clearly know that SomeValue is a non-static member variable of the same class.
So it doesn't just help you to ensure that name of your functions or variables wouldn't conflict with some other names, but it also makes it easier for others to read and understand the source code, writing a self documenting source code is sometimes very important as well.
Another case, that has arrived on the scenes after C++11 is in lambdas where this is captured.
You may have something like:
class Example
{
int x;
public:
std::function<void()> getIncrementor()
{
return [this] () -> void
{
++(this->x);
}
}
};
Although your lambda is generated within a class, it will only have access to local variables by capturing them (if your compiler does C++14) or capturing this. In the second case, inside the body of lambda, there simply is not x, but only this->x.
I don't think it makes a difference to the compiler, but I always write this-> because I believe it makes the code self-documenting.
Disambiguation: in case you have another similar naming function/variable in the same namespace? I've never seen usage for any other reason.
I prefer it without the explicit this pointer as well. For method calls it doesn't add a lot of value, but it helps distinguish local variables from member variables.
I can't quite remember the exact circumstances, but I've seen (very rare) instances where I had to write "this->membername" to successfully compile the code with GCC. All that I remember is that it was not in relation to ambiguity and therefore took me a while to figure out the solution. The same code compiled fine without using this-> in Visual Studio.
I will use it to call operators implicitly (the return and parameter types below are just dummies for making up the code).
struct F {
void operator[](int);
void operator()();
void f() {
(*this)[n];
(*this)();
}
void g() {
operator[](n);
operator()();
}
};
I do like the *this syntax more. It has a slightly different semantic, in that using *this will not hide non-member operator functions with the same name as a member, though.

Difference between static in C and static in C++??

What is the difference between the static keyword in C and C++?
The static keyword serves the same purposes in C and C++.
When used at file level (outside of a function), it sets the visibility of the item it's applied to. Static items are not visible outside of their compilation unit (e.g., to the linker). Their duration is the same as the duration of the program.
These file-level items (functions and data) should be static unless there's a specific need to access them from outside (and there's almost never a need to give direct access to data since that breaks the central tenet of encapsulation).
If (as your comment to the question indicates) this is the only use of static you're concerned with then, no, there is no difference between C and C++.
When used within a function, it sets the duration of the item. Again, the duration is the same as the program and the item continues to exist between invocations of that function.
It does not affect the visibility of that item since it's visible only within the function. An example is a random number generator that needs to keep its seed value between invocations but doesn't want that value visible to other functions.
C++ has one more use, static within a class. When used there, it becomes a single class variable that's common across all objects of that class. One classic example is to store the number of objects that have been instantiated for a given class.
As others have pointed out, the use of file-level static has been deprecated in favour of unnamed namespaces. However, I believe it'll be a cold day in a certain warm place before it's actually removed from the language - there's just too much code using it at the moment. And ISO C have only just gotten around to removing gets() despite the amount of time we've all known it was a dangerous function.
And even though it's deprecated, that doesn't change its semantics now.
The use of static at the file scope to restrict access to the current translation unit is deprecated in C++, but still acceptable in C.
Instead, use an unnamed namespace
namespace
{
int file_scope_x;
}
Variables declared this way are only available within the file, just as if they were declared static.
The main reason for the deprecation is to remove one of the several overloaded meanings of the static keyword.
Originally, it meant that the variable, such as in a function, would be given storage for the lifetime of the program in an area for such variables, and not stored on the stack as is usual for function local variables.
Then the keyword was overloaded to apply to file scope linkage. It's not desirable to make up new keywords as needed, because they might break existing code. So this one was used again with a different meaning without causing conflicts, because a variable declared as static can't be both inside a function and at the top level, and functions didn't have the modifier before. (The storage connotation is totally lost when referring to functions, as they are not stored anywhere.)
When classes came along in C++ (and in Java and C#) the keyword was used yet again, but the meaning is at least closer to the original intention. Variables declared this way are stored in a global area, as opposed to on the stack as for function variables, or on the heap as for object members. Because variables cannot be both at the top level and inside a class definition, extra meaning can be unambiguously attached to class variables. They can only be referenced via the class name or from within an object of that class.
It has the same meaning in both languages.
But C++ adds classes. In the context of a class (and thus a struct) it has the extra meaning of making the method/variable class members rather members of the object.
class Plop
{
static int x; // This is a member of the class not an instance.
public:
static int getX() // method is a member of the class.
{
return x;
}
};
int Plop::x = 5;
Note that the use of static to mean "file scope" (aka namespace scope) is only deoprecated by the C++ Standard for objects, not for functions. In other words,:
// foo.cpp
static int x = 0; // deprecated
static int f() { return 1; } // not deprecated
To quote Annex D of the Standard:
The use of the static keyword is
deprecated when declaring objects in
namespace scope.
You can not declare a static variable inside structure in C... But allowed in Cpp with the help of scope resolution operator.
Also in Cpp static function can access only static variables but in C static function can have static and non static variables...😊