Lecture 7: Statics Flashcards
Static variables
Lifetime: point of initalization til the end of the program
Declared and initialized only once
If static var is not initialized explicitly, it is initialized to
0 (of that data type)
Difference between const and static variables
Constant variables –> retain same value throughout the scope
Lifetime: initialization til end of scope
Access: initialization til end of scope
Static variables –> retain same memory location throughout the entire program
Lifetime: initialization til end of program
Access: only in the scope
Static data member/ static class member
Part of class, but not part of any individual object Shared by all instances of the class, instead of belonging to a single one Declared inside class Initialized outside class Created even no object of the class is created Remains in memory even after all objects of the respective class are deleted Used to store information that is required by all objects
Can a private static member be accessed outside the class?
Yes, but only when it is being initialized
Methods of accessing a static data member or function
- Like a normal data member or function(through any created object)
- Using scope resolution operator
Static member function
a member function of a class that does not require being called by any individual object can only access static data members
Why can a static member function only access static data members?
This pointer is not implicitly passed to static member functions –> cannot access the data members of whatever object we are trying to call them through
If pointer of the object is passed explicitly, then function can access data members
Can regular member functions access static data members?
Yes
Alternative to using static data members
Global variables.
Accessible to all, so go against data encapsulation