0% found this document useful (0 votes)
31 views

Static Data Member Static Member Function

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Static Data Member Static Member Function

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CI215:Object Oriented Design

and Programming Lab

Asst.Prof. Pragati P. Patil


Introduction to Object Oriented
Programming
• The Origin of C++
• Features of object oriented
• Class and objects
• Inline Functions
• Constructors & Destructors
• Parameterized constructors
• Static class members
• Scope resolution operators
• Passing objects to functions
• Nested classes
• Local classes
• Friend Functions
• Friend Classes
}

When to use Static Variable in C++?


• We should use a static variable whenever we want to
reuse the modified value of the variable inside a
function in the next function call.
• when we want all the objects to maintain a single copy
of the class variable.
• Syntax:
– static datatype variable_name //declaration
– Return_type class_name::variable_name= value; //define
– static return_type function_name() // declaration
{
// Static functions ...
}
#include <iostream>
using namespace std;
class Natural
{
public:
static int num;
void increase()
{
++num;
}
};
/* *It is important to initialize the static variable outside of a class *we do so by using the class name and scope resolution
operator. */
int Natural::num = 0;
int main()
{
Natural obj1; //Creating 1st object Output:
Num of 1st Object: 2
//Incrementing Natural::num 2 times
Num of 2nd Object: 2
obj1.increase();
obj1.increase();
cout << "Num of 1st Object: "<< obj1.num << endl;

Natural obj2; //Creating 2nd object

cout << "Num of 2nd Object: "<< obj2.num << endl;


return 0;
}
Example: static variable and
function
using namespace std;
class Base
{
public :
static int val;
static int func(int a)
{
cout << "\nStatic member function called"; cout << "\nThe value of a : " << a;
}
};
int Base::val=28;
int main()
{
Base b;
Base::func(8);
cout << "\nThe static variable value : " << b.val;
return 0;
}

Output
Static member function called
The value of a : 8
The static variable value : 28
#include <iostream>
using namespace std;

class Test
{
static int x; Answer: (C)
public:
Test() { x++; } Explanation: Static functions can be called
static int getX() {return x;}
without any object. So the call “Test::getX()” is
};
fine.
int Test::x = 0;
Since x is initialized as 0, the first call to getX()
int main() returns 0. Note the statement x++ in
{ constructor. When an array of 5 objects is
cout << Test::getX() << " "; created, the constructor is called 5 times. So x
Test t[5]; is incremented to 5 before the next call to
cout << Test::getX();
}
getX().

(A) 0 0
(B) 5 5
(C) 0 5
(D) Compiler Error

You might also like