does c++ create an instance when declare a static member? - c++

does c++ create an instance when declare a static member?
I think this is a concept question, maybe. I am not so sure.
I mean when I declare a class with a static member inside, would there be a real space for the static member? As I knew, a static member could only exit uniquely once in a class. Is the static space and function there after I declared it? If so, does it mean I can call a function (static?) without defining a real object?
Thanks

Yes, if you declare a static member, real space for it exists. It's basically like a global variable in that sense, except for the limited scope within which it's accessible.
Yes, you can call a static function without making an instance.

Actually instance of class is never created automatically.but even before creating an instance you can call that variable...static members are seperately treated common to all instances of a class.

Related

Purpose of a static member function in C++?

If each member function is only contained once per class (to be shared by all instances) what exactly is the purpose of declaring a member function static? Is it like a function being declared const, in that it modifies a particular type of data (in this case, static data members)?
Normal member functions require a class instance to run. Static methods can be called directly without first creating an instance of the class.
Normal method:
MyClass myClass;
myClass.NormalMethod();
Static method:
MyClass::StaticMethod();
So normal methods are perfect for functions that work with the class data. If a method doesn't need to work with the class data, then it would be a candidate for possibly being made static.
Class methods, static or otherwise, can access private members of any of that class's objects, not just its own instance. Same goes for static methods, which don't have an instance unless you pass one to them.
You could also use a free function and declare it a friend, but a free function implies a higher level of abstraction that may operate on objects of different classes. A static class method says "I only make sense in light of my class"
One application of static methods is to create instances and return pointers. For example, there may be derived classes that the caller isn't supposed to know about - the "factory" function knows which derived class to use.
Of course when you need to create an object, you probably don't already have an object to use for that, and even if you do that other object isn't relevant.
Basically, sometimes some action is an aspect of the abstraction that a class provides, but that action isn't associated with a specific object - or at least not one that already exists. In that case, you should implement the action as a static function.
Similarly, some data is related to the abstraction provided by a class but not to a particular instance of that class. That data is probably best implemented as static member variables.

Does it make any sense to declare a static variable in a class' function where the object is static

Lets say my class lets say I have
static classA myObject;
void classA::update(int elapsed)
{
static int sumElapsed = 0;
sumElapsed+= elapsed;
}
It seems that my questions is kind of hard to understand. But if we say that myObject is a singleton of classA. Is there a difference between the local static int sumElapsed and a private member int sumElapsed of the classA, other than the scope in which they can get accessed.
Sure. For example in the singleton pattern. There a reference (or pointer) to the static variable is also returned from a static method.
For an example see here: c++ Meyers singleton undefined reference
By the way, if you are interested: Are Singletons really that bad?
If you don't want sumElapsed to be overwritten then yes, but it does seem like it would make more sense to have sumElapsed ecapsulated within classA as a static variable.
Effectively, when you need some sort of a static member in a class template there aren't really good alternatives in the first place. Also, if the members aren't trivial you probably want to put them into a function in the first place to have some level of control over the order of initialization.
In general, be aware that whether you put a static member into a class or into a function, it is still effectively implementing the Singleton anti-pattern!
Of course. If sumElapsed isn't static, it will get overwritten every time the function is called; as it is, it won't be. The fact that classA::update is itself static is irrelevant; just consider if it was a global function (e.g. in C).
You should use a static class to hold methods that are not associated with a particular object. That being said, use a static class to hold only static members that cannot be instantiated by objects, and shouldn't be overwritten.

Difference between static method and non static function in memory

As I understand, each instance of a class has its own member variables in memory, so that it can store different values for different objects. However, it is not the same for member functions. Member functions are reused across objects of a class, so it only has one address with one block of memory to refer when needed by all objects.
Static function is made to access static members. However, static function also exists only one during the lifetime of its application. Aside from being the static accessor, at low level it is not different with normal class functions, isn't it? Or maybe I'm wrong, that each class has its own functions?
Non-static functions accept additional parameter, this, which is the pointer to the class instance with the instance-specific variables.
Static functions don't have this parameter (thus you can't use this in a static function and can only access static data members).
This differs from language to language, but in C or C++03 functions generally map on assembly functions; that is they exist once in memory (whether free functions, class functions or class static functions) and take arguments as parameters, including a this pointer for member functions that is implicit.
In C++11, lambda functions introduce a novelty: each instance of the so-called function will carry some state. From an implementation point of view, it therefore means that a "regular" function needs be created and it is associated to an anonymous bundle of data (if necessary). The function need not be duplicated each time the lambda is created, but the data does. One helpful figure is to remember that lambdas (in C++) replace function objects (or predicate objects): they are just syntactic sugar, the implementation is similar.
The only difference between static and member functions is that member functions always have the this pointer passed in automatically.
simply if it is referred, static functions creates a single set of memory for itself and are meant for static data-members which are generally not changeable. But non-static functions creates separate set of memories for each instances and are meant for both non-static and static data-members. If u require stable output go for static and if u require the alternate go for the non-static.

Restrictions on local variable usage in C++?

I had a few questions in a technical interview that I thought I knew, but wanted to double-check (they said I passed it, but I was unsure about these):
A variable declared inside a Class Method... Can that be used outside of that method, like for instance in another method? (I said no)
Can a variable declared inside a method be passed as a parameter to another method?
(I said yes but I wasn't sure)
This is for an entry-level C++ position and I'm used to C, so I wanted to double-check my understanding of C++/OO concepts.
A variable within a class method, that's instantiated within that method and wholly contained within that method, can only be used within that method. Its lifetime is finite. Edit: to clarify, I'm not saying it can't be passed to another function call within the function scope and I'm not talking about instantiating a member variable or static variable.
Yes, you can pass it to another method if that method is called from within the method it exists. Why? Because its lifetime it tied to the parent method, not the one that is called from within the method.
Let me illustrate:
//aVar does not exist.
int foo(){
int aVar = 1; //it's been born
cout << doSomething(aVar); // still alive
return aVar; //still alive but a copy is being returned from the function. Not aVar itself!
} // it's dead, man
Normally a variable's lifetime is inside the block it's declared in. So at the end of the scope it is destroyed.
BUT there's the case of Static Local Variable which is declared inside a method, but the value is saved in memory after the block is finished. Every call to that function will "see" the value of that variable. So, you could have a trick question, that the variable CAN be used in another instance of that method.
Yes you can pass it.
Contrary to popular belief, a variable declared in a member function can be used in another member function. There are two obvious routes to this.
The first is if that member function calls another member function, passing a pointer or reference to that variable to the second member function. The variable exists from the time the first member function is called until it exits from that call; if it calls some other function during that time, that other code can use the variable (if the member function does something to give it access).
The second is if you're dealing with a static variable defined in a member function. This is (for one example) the essence of the Meyers singleton. A static variable is defined in a member function, and not only other members of the singleton, but in fact all the rest of the program that accesses the singleton object use the static variable defined in that member function.
For the second question, you're right -- a variable defined in a member function is pretty much like any other local variable. It can be passed as a parameter, just like anything else.
First Question: Yes, you are correct. Variables declared within the scope of a class method are only valid in that scope. When the method exits, that variable loses scope and is no longer usable.
Second Question: Yes, the method can call another method, using that locally scoped variable. The variable remains in scope and is usable through the duration of the second function call.
First of all.....a variable declared
inside a Class Method....can that be
used outside of that method, like for
instance in another method
In C++, no.
Secondly, can a variable declared
inside a method be passed as a
parameter for another method?
In C++, in a non-concurrent application, yes. In the case of concurrency and the receiving function takes its parameter by reference you must make sure the object you pass doesn't destruct while the receiving function uses it.
First of all.....a variable declared inside a Class Method....
can that be used outside of that method,
like for instance in another method
Sure. For example,
class Base {
public:
static Base *create_instance() {
static int variable_declared_inside_class_method = 0;
return new Base(variable_declared_inside_class_method);
}
Base(int &var_) : var(var_) {}
int inc_var() {
var++; // this method uses variable_declared_inside_class_method
}
private:
int &var;
};
Note that variable_declared_inside_class_method does not live on the stack. This is why it works here.
Secondly, can a variable declared inside a method be passed as a parameter
for another method?
Absolutely.

static variable vs. member

If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variable a local static variable of the routine that it is in or make it a member of the class?
The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.
I would argue that in most cases, you should never use a local static variable, and instead use a static member variable. Then the question degenerates to if that variable should be shared among the class instances or not.
Declaring a local variable as static means your method now has state, separate from the object's state. It can lead to many mistakes when maintaining this code (such as copy constructor implementation, assignment, serialization) and when reading it (unclear method behavior).
Avoid using static locals unless you have some good reason (the only one I can think of is single threaded singletone implementation).