Calling member function without creating object in C++ - c++

Can anyone explain why we can call static member functions without creating instance of an object but we can't in case of non-static functions?
I searched everywhere, I couldn't find an explanation, Can you help?

You've got the logic basically in reverse. It is useful to have functions that belong to a class, even though they do not need to be called on an object of that class. Stroustrup didn't want to add a new keyword for that, so he repurposed the existing keyword static to distinguish such methods from normal methods.
In hindsight, other options could have been chosen. We could have made this an explicit function argument for the normal methods, for instance. But that's about 30 years too late now.

Why?
Because we like encapsulation and modularity which we get when using object orientated patterns.
You can view static class member functions and variables as a way of encapsulating what would otherwise have been global functions and variables - which might collide.
Underneath, there is not a great deal of difference between a plain old C++ file with some functions declared and implemented in it, to a class filled with only static functions. The difference is we can cleanly access a set of functions attached to a parent class.
An example:
Suppose you want to create a new class like MyMediumInteger, and you want developers to determine what the maximum number it can hold is. This information is applicable for every instance of MyMediumInteger, no matter what the state of the private member variables are. Therefore it makes sense to expose this information without forcing the developer to instantiate the class. Your options include defining something global such as #define MYMEDIUMINTEGER_MAX ... which could collide with a define sharing the same name in another module, or create a static function returning the max size, called neatly via
MyMediumInteger::maxSize().
A code example:
/***
* Use a static class member function (or variable)
*/
class MyMediumInteger
{
public:
static unsigned long maxSize() { return pow(2, 32) - 1; };
};
auto maxSize = MyMediumInteger::maxSize();
/**
* Alternative approaches.
* Note: These could all collide with other #defines or symbols declared/implemented in other modules.
* Note: These are both independant sources of information related to a class - wouldn't it be nicer if they could just belong to the class instead?
*/
/***
* Use a #define
*/
#define MYMEDIUMINTEGER_MAX (pow(2, 32) - 1)
auto maxSize = MYMEDIUMINTEGER_MAX;
/**
* Use a global function or variable
*/
static unsigned long getMyMediumIntegerMaxSize()
{
return pow(2, 32) - 1;
}
auto maxSize = getMyMediumIntegerMaxSize();
A word of warning:
Static member variables and functions have some of the pitfalls of global variables - because they persist through instances of classes, calling and assigning to them can cause unexpected side effects (because static member variables get changed for everyone, not just you).
A common pitfall is to add lots of static member functions and variables for management - for example, maintaining a list of all other class instances statically which gets appended to in the constructor of each class. Often this type of code could be refactored into a parent class whose job it is just to manage instances of the child class. The latter approach is far more testable and keeps things modular - for example, someone else could come along and write a different implementation of the management code without appending to or re-writing your child class implementation.
How?
In C++ class member functions are not actually stored in class instances, they are stored separately and called on instances of classes. Therefore, it's not hard to imagine how static functions fit into this - they are declared in the same way as normal class member functions, just with the static keyword to say "I don't need to be given a class instance to be run on". The consequence of this is it can't access class member variables or methods.

Static member functions does not need a "this" pointer, it belongs to the class.
Non-static functions need a "this" pointer to point out in which object it belong to, so you need to creat a object firstly.

Because that's what static means: "I don't want this function to require an object to work on".
That's the feature. That's its definition.
Any other answer would be circular.
Why is it useful? Sometimes we want to be able to "organise" some data or utilities in our classes, perhaps for use by external code or perhaps for use by non-static functions of the same class. In that sense there is some crossover with namespaces.

Related

A c++ class include a static member with the same type of itself. Why this pattern?

I inherited a project from a former colleague, and I found these code snippets (and some similar ones in SO questions: can a c++ class include itself as an member and static member object of a class in the same class)
// Service.h
class Service
{
// ...
public:
static Service sInstance;
void Somememberfunc();
//...
};
// Service.cpp
#include "Service.h"
Service Service::sInstance;
void Service::Somememberfunc()
{
//...
}
// Main.cpp
#include "Service.h"
void Fun()
{
Service &instance = Service::sInstance;
//...
instance.Somememberfunc();
//...
}
However, I did not find any explanation on when to use this pattern. And what are the advantages and disadvantages?
Notice that the member is a static, so it's part of the class, not of instantiated objects. This is important, because otherwise you would be trying to make a recursive member (since the member is part of the object, it also contains the same member and so on...), but this is not the case here.
The best pattern to describe this is: global variable. The static member is initialized before main() and can be accessed from any part of the program by including the header file. This is very convenient while implementing but becomes harder to handle the more complex the program gets and the longer you have to maintain it, so the general idea is to avoid this. Also, because there is no way to control the order of initialization, dependencies between different global variables can cause problems during startup.
Static member is roughly a global variable in the scope of the class.
Static members have also the advantage of visibility access (public/protected/private) to restreint its usage (file scope might be an alternative).
That member might be of type of the class.
Global are "easy" to (mis)use, as they don't require to think about architecture.
BUT (mutable) global are mostly discouraged as harder to reason about.
Acceptable usages IMO are for constants:
as for a matrix class, the null matrix, the diagonal one matrix.
for Temperature class, some specific value (absolute 0 (O Kelvin), temperature of water transformation(0 Celsius, 100 Celsius), ...)
in general NullObject, Default, ...
Singleton pattern. For example, you can use it to store your app configurations. And then you can easily access configurations anywhere(globally) within your app.
This is often used in the singleton design pattern
Visit https://en.wikipedia.org/wiki/Singleton_pattern

Free functions vs singleton vs static class members [duplicate]

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Should members of a class be turned static when more than one object creation is not needed?

class AA
{
public:
AA ();
static void a1 ();
static std :: string b1 ();
static std :: string c1 (unsigned short x);
};
My class won't have different objects interacting with among themselves or with others.
Of course I need to have at least one object to call the functions of this class, so I thought of making the members static so that unnecessary object creation can be avoided.
What are the pros and cons of this design? What will be a better design?
To access to static members, you don't even need an object, just call
AA::a1()
This patterns is called "Monostate", the alternative being Singleton, where you actually create an object, but make sure it's only done once, there are tons of tutorials on how to do that, just google it.
Should members of a class be turned static when more than one object creation is not needed?
You make members of the class static when you need only one instance of the member for all objects of your class. When you declare a class member static the member becomes per class instead of per object.
When you say you need only one object of your class, You are probably pointing towards the singleton design pattern. Note that pattern is widely considered an anti pattern and its usefulness if any is dependent to specific situations.
The reason you mention in Q is no way related to whether you should make a member static or not.
Your class has no data members, so I don't see any good reason to use a class at all:
namespace AA
{
void a1 ();
std :: string b1 ();
std :: string c1 (unsigned short x);
};
Of course I need to have at least one object to call the functions of this class
That's not true. You can call static member functions without an instance of the class.
A note on the Singleton pattern: it has a bad reputation, it is often mis-used, and in my experience it is only very rarely useful. What it does is enforce that there can only be one instance of the class, and that this instance is globally accessible.
People often think, "I only need one instance, therefore I should use Singleton", especially when Singleton is the first Capitalized Design Pattern they're introduced to. This is wrong -- if you only need one instance, create one instance and use it. Don't unnecessarily limit all future users of the class to only create one instance. Don't unnecessarily create shared global state. Both things make your code less flexible, harder to use in different ways and therefore in particular harder to test. Some people would argue that for these reasons, Singleton is strictly never useful.
In this case you don't seem to need even one instance. If that's the case I'd use free functions as above.

C++, static vs. namespace vs. singleton

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Is using too much static bad or good?

I like to use static functions in C++ as a way to categorize them, like C# does.
Console::WriteLine("hello")
Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?
What about static const?
but is it good or bad
The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?
The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
I'm all for using static functions. These just make sense especially when organized into modules (static class in C#).
However, the moment those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.
In a nutshell: static functions ok, static data bad.
Those who say static functions can be replaced by namespaces are wrong, here is a simple example:
class X
{
public:
static void f1 ()
{
...
f2 ();
}
private:
static void f2 () {}
};
As you can see, public static function f1 calls another static, but private function f2.
This is not just a collection of functions, but a smart collection with its own encapsulated methods. Namespaces would not give us this functionality.
Many people use the "singleton" pattern, just because it is a common practice, but in many cases you need a class with several static methods and just one static data member. In this case there is no need for a singleton at all. Also calling the method instance() is slower than just accessing the static functions/members directly.
Use namespaces to make a collection of functions:
namespace Console {
void WriteLine(...) // ...
}
As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.
One specific reason static data is bad, is that C++ makes no guarantees about initialization order of static objects in different translation units. In practice this can cause problems when one object depends on another in a different translation unit. Scott Meyers discusses this in Item 26 of his book More Effective C++.
Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :)
To put it really into perspective.. Functional Programming ;)
The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like:
public class TotalManager
{
public double getTotal(Hamburger burger)
{
return burger.getPrice() + burget.getTax();
}
}
...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.
I tend to make classes that consist of static functions, but some say the "right way" to do this is usually to use namespaces instead. (I developed my habits before C++ had namespaces.)
BTW, if you have a class that consists only of static data and functions, you should declare the constructor to be private, so nobody tries to instantiate it. (This is one of the reasons some argue to use namespaces rather than classes.)
For organization, use namespaces as already stated.
For global data I like to use the singleton pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.
Also be sure that your static functions are stateless so that they are thread safe.
I usually only use statics in conjunction with the friend system.
For example, I have a class which uses a lot of (inlined) internal helper functions to calculate stuff, including operations on private data.
This, of course, increases the number of functions the class interface has.
To get rid of that, I declare a helper class in the original classes .cpp file (and thus unseen to the outside world), make it a friend of the original class, and then move the old helper functions into static (inline) member functions of the helper class, passing the old class per reference in addition to the old parameters.
This keeps the interface slim and doesn't require a big listing of free friend functions.
Inlining also works nicely, so I'm not completely against static.
(I avoid it as much as I can, but using it like this, I like to do.)