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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With