Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
Amumu Avatar asked Oct 05 '11 05:10

Amumu


People also ask

What is the difference between static and non static members?

static members are accessed by their class name which encapsulates them, but non-static members are accessed by object reference. static members can't use non-static methods without instantiating an object, but non-static members can use static members directly.

Do static methods take up more memory?

Yes, static data will in a sense save memory since there's only a single copy of it. Of course, whether or not data should be static is more a function of the meaning or use of the data, not memory savings.

What is the difference between static member function and non static member function?

A static member function can be called, even when a class is not instantiated. A static member function cannot have access to the this pointer of the class. A non-static member function can be declared as virtual but care must be taken not to declare a static member function as virtual.

What is the difference between the static and the non static variables of a class explain it with an example?

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.


1 Answers

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).

like image 106
littleadv Avatar answered Sep 24 '22 23:09

littleadv