Professional Documents
Culture Documents
Lecture 4 Static Components
Lecture 4 Static Components
int main()
{
for(int i = 0; i < 5; i++)
fun();
}
Behavior of Static Variables
• Variable var is created and initialized once during program
initialization
• Preserves its value between subsequent function invocations
• Output will be:
var = 100
var = 101
var = 102
var = 103
var = 104
Class Instances
• Each object created from a class #include <iostream>
using namespace std;
is an instance of that class
class Class {
• Instances encapsulate all public:
components (fields and int val;
void print()
functions) of the class {
cout << val << endl;
• Attempting to access non- }
existent components outside the };
error: }
Static Components
• Static components exist #include <iostream>
using namespace std;
the class
void print()
{
cout << "Static = " << ++Static << ", NonStatic = " << NonStatic << endl;
class functions: {
cout << Counter << " instances" << endl;
• Output };
}
2 instances {
Class::HowMany();
4 instances Class a;
Class b;
Bye, bye! b.HowMany();
Class c;
Class d;
d.HowMany();
}
Static vs. non-static components
• To analyze the interactions between static
and non-static components, we'll consider
four scenarios: