Reference-Material-I

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Static in C++

Static is a keyword in C++ used to give special characteristics to an


element. Static elements are allocated storage only once in a
program lifetime in static storage area. And they have a scope till
the program lifetime. Static Keyword can be used with following,

1. Static variable in functions

2. Static Class Objects

3. Static member Variable in class

4. Static Methods in class

An example of memory use


Consider the following example of a program containing all three
forms of memory:
#include <stdio.h>
#include <stdlib.h>

int x;

int main(void)
{
int y;
char *str;

y = 4;
printf("stack memory: %d\n", y);

str = malloc(100*sizeof(char));
str[0] = 'm';
printf("heap memory: %c\n", str[0]);
free(str);
return 0;
}
The variable x is static storage, because of its global nature.
Both y and str are dynamic stack storage which is deallocated when
the program ends. The function malloc() is used to allocate 100
pieces of of dynamic heap storage, each the size of char, to str.
Conversely, the function free(), deallocates the memory associated
with str.
REPORT THIS AD
Static Variables inside Functions

Static variables when used inside function are initialized only once,
and then they hold there value even through function calls.

These static variables are stored on static storage area , not in stack.

void counter()

static int count=0;

cout << count++;

int main()

for(int i=0;i<5;i++)

counter();

0 1 2 3 4
Let's se the same program's output without using static variable.

void counter()

int count=0;

cout << count++;

int main(0

for(int i=0;i<5;i++)

counter();

0 0 0 0 0
If we do not use static keyword, the variable count, is reinitialized
everytime when counter() function is called, and gets destroyed each
time when counter() functions ends. But, if we make it static, once
initialized count will have a scope till the end of main() function and
it will carry its value through function calls too.
If you don't initialize a static variable, they are by default initialized
to zero.

Static Members of a C++ Class


We can define class members static using static keyword. When
we declare a member of a class as static it means no matter how
many objects of the class are created, there is only one copy of
the static member.
A static member is shared by all objects of the class.
All static data is initialized to zero when the first object is
created, if no other initialization is present.
We can't put it in the class definition but it can be initialized
outside the class as done in the following example by redeclaring
the static variable, using the scope resolution operator :: to
identify which class it belongs to.
class X
{
public:
static int i;
X()
{
// construtor
};
};

int X::i=1;

int main()
{
X obj;
cout << obj.i; // prints value of i
}

In the above figure number is a non static member of a class and


count is static member.

#include <iostream>
using namespace std;

class Box {
public:
static int objectCount;

// Constructor definition
Box(double l = 5.0, double b = 5.0, double h = 5.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;

// Increase every time object is created


objectCount++;
}
double Volume() {
return length * breadth * height;
}
void display ()
{
cout<<length<<" ";
cout<<breadth<<" ";
cout<<height<<endl;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0); // Declare box2
Box Box3;
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
Box1.display();
Box2.display();
Box3.display();
return 0;
}

Static Function Members


By declaring a function member as static, you make it
independent of any particular object of the class.

A static member function can be called even if no objects of the


class exist and the static functions are accessed using only the
class name and the scope resolution operator ::.

A static member function can only access static data member,


other static member functions and any other functions from
outside the class.

Static member functions have a class scope and they do not have
access to the this pointer of the class. You could use a static
member function to determine whether some objects of the class
have been created or not.

class X
{

public:

static void f()

// statement

};

int main()

X::f(); // calling member function directly with class


name

Let us try the following example to understand the concept of


static function members −

Live Demo
#include <iostream>

using namespace std;

class Box {
public:
static int objectCount;

// Constructor definition
Box(double l = 2.0, double b = 2.0, double h =
2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
return length * breadth * height;
}
static int getCount() {
return objectCount;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;

int main(void) {
// Print total number of objects before creating
object.
cout << "Inital Stage Count: " << Box::getCount() <<
endl;

Box Box1(3.3, 1.2, 1.5); // Declare box1


Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects after creating


object.
cout << "Final Stage Count: " << Box::getCount() <<
endl;

return 0;
}

When the above code is compiled and executed, it produces the


following result −

Inital Stage Count: 0


Constructor called.
Constructor called.
Final Stage Count: 2
Static Class Objects

Static keyword works in the same way for class objects too. Objects
declared static are allocated storage in static storage area, and have
scope till the end of program.

Static objects are also initialized using constructors like other


normal objects.

Non static Object:

#include<iostream>
using namespace std;
class Sam
{
int m = 0;
public:
Sam()
{
m = 0;
cout << "javatpoint\n";
}
~Sam()
{
cout << "Data Science\n";
}
};
int main()
{
int o = 0;
if (o==0)
{
Sam nex;
}
cout << "Machine Learning\n";
}

Output:
javatpoint
Data Science
Machine Learning

Static object
#include<iostream>
using namespace std;
class Sam
{
int m = 0;
public:
Sam()
{
m = 0;
cout << "javatpoint\n";
}
~Sam()
{
cout << "Data Science\n";
}
};
int main()
{
int o = 0;
if (o==0)
{
static Sam nex;
}
cout << "Machine Learning\n";
}

Output:

javatpoint

Machine Learning

Data Science

If the object had been created as a non-static object, then the scope of the variable
would have been only inside the if block, and as soon as the control of the if the
block had gotten over, the destructor would have been invoked. This problem must
be avoided, so the object has to be created static as it has been done in the program.
This has made the destructor gets invoked once the main has ended. It is only
possible because of the static object and its scope throughout the program's lifetime.

class Abc

int i;

public:

Abc()

i=0;

cout << "constructor";


}

~Abc()

cout << "destructor";

};

void f()

static Abc obj;

int main()

int x=0;

if(x==0)

f();

cout << "END";


}

Output:

constructor

END

destructor

You must be thinking, why was the destructor not called upon the
end of the scope of if condition, where the reference of
object obj should get destroyed. This is because object was static,
which has scope till the program's lifetime, hence destructor for this
object was called when main() function exits.

You might also like