SlideShare a Scribd company logo
1 of 8
Download to read offline
Static Keyword 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, Static
variable in functions Static Class Objects Static member Variable in class Static Methods in class
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(0 { for(int i=0;i<5;i++) { counter(); } } Output : 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(); } } Output : 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 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. Assignment to zero, on using static
keyword is only for primitive datatypes, not for user defined datatypes. 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 destructor not called upon the end of the scope of if
condition. This is because object was static, which has scope till the program lifetime, hence
destructor for this object was called when main() exits. Static data member in class Static data
members of class are those members which are shared by all the objects. Static data member has
a single piece of storage, and is not available as separate copy with each object, like other non-
static data members. Static member variables (data members) are not initialied using constructor,
because these are not dependent on object initialization. Also, it must be initialized explicitly,
always outside the class. If not initialized, Linker will give error. class X { static int i; public:
X(){}; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i } Once the definition for
static data member is made, user cannot redefine it. Though, arithmetic operations can be
performed on it. Static Member Functions These functions work for the class as whole rather
than for a particular object of a class. It can be called using an object and the direct member
access . operator. But, its more typical to call a static member function by itself, using class name
and scope resolution :: operator. Example : class X { public: static void f(){}; }; int main() {
X::f(); // calling member function directly with class name } These functions cannot access
ordinary data members and member functions, but only static data members and static member
functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary
members. We will study about "this" keyword later. n the lesson on file scope and the static
keyword, you learned that static variables keep their values and are not destroyed even after they
go out of scope. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include int generateID() {
static int s_id = 0; return ++s_id; } int main() { std::cout << generateID() << ' '; std::cout <<
generateID() << ' '; std::cout << generateID() << ' '; return 0; } This program prints: 1 2 3
Note that s_id has kept its value across multiple function calls. The static keyword has another
meaning when applied to global variables -- it gives them internal linkage (which restricts them
from being seen/used outside of the file they are defined in). Because global variables are
typically avoided, the static keyword is not often used in this capacity. Static member variables
C++ introduces two more uses for the static keyword when applied to classes: static member
variables, and static member functions. Fortunately, these uses are fairly straightforward. We’ll
talk about static member variables in this lesson, and static member functions in the next. Before
we go into the static keyword as applied to member variables, first consider the following class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Something { public: int m_value = 1; }; int
main() { Something first; Something second; second.m_value = 2; std::cout << first.m_value
<< ' '; std::cout << second.m_value << ' '; return 0; } When we instantiate a class object, each
object gets its own copy of all normal member variables. In this case, because we have declared
two Something class objects, we end up with two copies of m_value: first.m_value, and
second.m_value. first.m_value is distinct from second.m_value. Consequently, the program
above prints: 1 2 Member variables of a class can be made static by using the static keyword.
Unlike normal member variables, static member variables are shared by all objects of the class.
Consider the following program, similar to the above: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 class Something { public: static int s_value; }; int Something::s_value = 1; int main() {
Something first; Something second; second.s_value = 2; std::cout << first.s_value << ' ';
std::cout << second.s_value << ' '; return 0; } This program produces the following output: 2 2
Because s_value is a static member variable, s_value is shared between all objects of the class.
Consequently, first.s_value is the same variable as second.s_value. The above program shows
that the value we set using first can be accessed using second! if static or global, indeterminate if
storage class is auto C has always been very specific about the initial values of objects. If global
or static, they will be zeroed. If auto, the value is indeterminate. This was the case in pre-C89
compilers and was so specified by K&R and in DMR's original C report. This was the case in
C89, see section 6.5.7 Initialization. If an object that has automatic storage duration is not
initialized explicitely, its value is indeterminate. If an object that has static storage duration is not
initialized explicitely, it is initialized implicitely as if every member that has arithmetic type
were assigned 0 and every member that has pointer type were assigned a null pointer constant.
This was the case in C99, see section 6.7.8 Initialization. If an object that has automatic storage
duration is not initialized explicitly, its value is indeterminate. If an object that has static storage
duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a null
pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an
aggregate, every member is initialized (recursively) according to these rules; — if it is a union,
the first named member is initialized (recursively) according to these rules. As to what exactly
indeterminate means, I'm not sure for C89, C99 says: indeterminate value either an unspecified
value or a trap representation But regardless of what standards say, in real life, each stack page
actually does start off as zero, but when your program looks at any auto storage class values, it
sees whatever was left behind by your own program when it last used those stack addresses. If
you allocate a lot of auto arrays you will see them eventually start neatly with zeroes. n general,
what doesn't change with something that is static in a programming language is whether it is
alive or not. Static variables are always alive; they have a single instance which comes into being
either at the beginning of the program or the first time they are visible, and lasts until the end of
the program. Non-static variables come and go, as blocks are entered and left, or as class
instances are created and destroyed. In C++, for reasons of C compatibility, static, when applied
to variables at namespace scope, has a completely unrelated meaning: it means that the variable
has internal, rather than external linkage, and is not visible in other translation units. Why the
word static was adopted for this in early C, I don't know; I can only guess that they needed
something, and didn't want to introduce a new keyword. (Originally, in the very earliest versions
of C, variables at file scope obeyed the rules of a Fortran named common block: all variables of
the same name referred to the same storage.) Looking back, of course (with 20/20 hindsight), the
default for variables at file scope should have been internal linkage, with a special keyword
(public?) to say that the variable had external linkage. But this was a lot less obvious in the early
1970's. 2 down vote Static is referred to the variable storage. Inside a function call, every
variable that you declare is pushed on the stack. Unlike other variables, a static variable isn't
pushed on the stack, it's like a global variable, that survives the whole execution of the program,
with the difference that is visible only inside the block is declared. Friend Functions A C++
friend functions are special functions which can access the private members of a class. They are
considered to be a loophole in the Object Oriented Programming concepts, but logical use of
them can make them useful in certain cases. For instance: when it is not possible to implement
some function, without making private members accessible in them. This situation arises mostly
in case of operator overloading. In the following example, the friend function print is a member
of class TWO and accesses the private data members a and b of class ONE. #include using
namespace std; //Must be known to TWO //before declaration of ONE. class ONE; class TWO {
public: void print(ONE& x); }; class ONE { int a, b; friend void TWO::print(ONE& x); public:
ONE() : a(1), b(2) { } }; void TWO::print(ONE& x) { cout << "a is " << x.a << endl; cout <<
"b is " << x.b << endl; } int main() { ONE xobj; TWO yobj; yobj.print(xobj); } Friend
functions have the following properties: 1) Friend of the class can be member of some other
class. 2) Friend of one class can be friend of another class or all the classes in one program, such
a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members
of the class in which they are declared to be friend, but they can use the members for a specific
object. 4) Friends are non-members hence do not get “this” pointer. 5) Friends, can be friend of
more than one class, hence they can be used for message passing between the classes. 6) Friend
can be declared anywhere (in public, protected or private section) in the class. Friend Class A
class can also be declared to be the friend of some other class. When we create a friend class then
all the member functions of the friend class also become the friend of the other class. This
requires the condition that the friend becoming class must be first declared or defined (forward
declaration). #include using namespace std; class MyClass { // Declare a friend class friend
class SecondClass; public: MyClass() : Secret(0){} void printMember() {
cout << Secret << endl; } private: int Secret; }; class SecondClass { public: void
change( MyClass& yourclass, int x ) { yourclass.Secret = x; } }; void main() {
MyClass my_class; SecondClass sec_class; my_class.printMember(); sec_class.change(
my_class, 5 ); my_class.printMember(); } Note:we declared friend class SecondClass; in the
class MyClass, so we can access Secret in the class SecondClass. Another property of friendships
is that they are not transitive: The friend of a friend is not considered to be a friend unless
explicitly specified. A friend function is used for accessing the non-public members of a class. A
class can allow non-member functions and other classes to access its own private data, by
making them friends. Thus, a friend function is an ordinary function or a member of another
class. A friend class has full access of private data members of another class without being
member of that class.
Solution
Static Keyword 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, Static
variable in functions Static Class Objects Static member Variable in class Static Methods in class
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(0 { for(int i=0;i<5;i++) { counter(); } } Output : 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(); } } Output : 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 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. Assignment to zero, on using static
keyword is only for primitive datatypes, not for user defined datatypes. 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 destructor not called upon the end of the scope of if
condition. This is because object was static, which has scope till the program lifetime, hence
destructor for this object was called when main() exits. Static data member in class Static data
members of class are those members which are shared by all the objects. Static data member has
a single piece of storage, and is not available as separate copy with each object, like other non-
static data members. Static member variables (data members) are not initialied using constructor,
because these are not dependent on object initialization. Also, it must be initialized explicitly,
always outside the class. If not initialized, Linker will give error. class X { static int i; public:
X(){}; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i } Once the definition for
static data member is made, user cannot redefine it. Though, arithmetic operations can be
performed on it. Static Member Functions These functions work for the class as whole rather
than for a particular object of a class. It can be called using an object and the direct member
access . operator. But, its more typical to call a static member function by itself, using class name
and scope resolution :: operator. Example : class X { public: static void f(){}; }; int main() {
X::f(); // calling member function directly with class name } These functions cannot access
ordinary data members and member functions, but only static data members and static member
functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary
members. We will study about "this" keyword later. n the lesson on file scope and the static
keyword, you learned that static variables keep their values and are not destroyed even after they
go out of scope. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include int generateID() {
static int s_id = 0; return ++s_id; } int main() { std::cout << generateID() << ' '; std::cout <<
generateID() << ' '; std::cout << generateID() << ' '; return 0; } This program prints: 1 2 3
Note that s_id has kept its value across multiple function calls. The static keyword has another
meaning when applied to global variables -- it gives them internal linkage (which restricts them
from being seen/used outside of the file they are defined in). Because global variables are
typically avoided, the static keyword is not often used in this capacity. Static member variables
C++ introduces two more uses for the static keyword when applied to classes: static member
variables, and static member functions. Fortunately, these uses are fairly straightforward. We’ll
talk about static member variables in this lesson, and static member functions in the next. Before
we go into the static keyword as applied to member variables, first consider the following class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Something { public: int m_value = 1; }; int
main() { Something first; Something second; second.m_value = 2; std::cout << first.m_value
<< ' '; std::cout << second.m_value << ' '; return 0; } When we instantiate a class object, each
object gets its own copy of all normal member variables. In this case, because we have declared
two Something class objects, we end up with two copies of m_value: first.m_value, and
second.m_value. first.m_value is distinct from second.m_value. Consequently, the program
above prints: 1 2 Member variables of a class can be made static by using the static keyword.
Unlike normal member variables, static member variables are shared by all objects of the class.
Consider the following program, similar to the above: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 class Something { public: static int s_value; }; int Something::s_value = 1; int main() {
Something first; Something second; second.s_value = 2; std::cout << first.s_value << ' ';
std::cout << second.s_value << ' '; return 0; } This program produces the following output: 2 2
Because s_value is a static member variable, s_value is shared between all objects of the class.
Consequently, first.s_value is the same variable as second.s_value. The above program shows
that the value we set using first can be accessed using second! if static or global, indeterminate if
storage class is auto C has always been very specific about the initial values of objects. If global
or static, they will be zeroed. If auto, the value is indeterminate. This was the case in pre-C89
compilers and was so specified by K&R and in DMR's original C report. This was the case in
C89, see section 6.5.7 Initialization. If an object that has automatic storage duration is not
initialized explicitely, its value is indeterminate. If an object that has static storage duration is not
initialized explicitely, it is initialized implicitely as if every member that has arithmetic type
were assigned 0 and every member that has pointer type were assigned a null pointer constant.
This was the case in C99, see section 6.7.8 Initialization. If an object that has automatic storage
duration is not initialized explicitly, its value is indeterminate. If an object that has static storage
duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a null
pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an
aggregate, every member is initialized (recursively) according to these rules; — if it is a union,
the first named member is initialized (recursively) according to these rules. As to what exactly
indeterminate means, I'm not sure for C89, C99 says: indeterminate value either an unspecified
value or a trap representation But regardless of what standards say, in real life, each stack page
actually does start off as zero, but when your program looks at any auto storage class values, it
sees whatever was left behind by your own program when it last used those stack addresses. If
you allocate a lot of auto arrays you will see them eventually start neatly with zeroes. n general,
what doesn't change with something that is static in a programming language is whether it is
alive or not. Static variables are always alive; they have a single instance which comes into being
either at the beginning of the program or the first time they are visible, and lasts until the end of
the program. Non-static variables come and go, as blocks are entered and left, or as class
instances are created and destroyed. In C++, for reasons of C compatibility, static, when applied
to variables at namespace scope, has a completely unrelated meaning: it means that the variable
has internal, rather than external linkage, and is not visible in other translation units. Why the
word static was adopted for this in early C, I don't know; I can only guess that they needed
something, and didn't want to introduce a new keyword. (Originally, in the very earliest versions
of C, variables at file scope obeyed the rules of a Fortran named common block: all variables of
the same name referred to the same storage.) Looking back, of course (with 20/20 hindsight), the
default for variables at file scope should have been internal linkage, with a special keyword
(public?) to say that the variable had external linkage. But this was a lot less obvious in the early
1970's. 2 down vote Static is referred to the variable storage. Inside a function call, every
variable that you declare is pushed on the stack. Unlike other variables, a static variable isn't
pushed on the stack, it's like a global variable, that survives the whole execution of the program,
with the difference that is visible only inside the block is declared. Friend Functions A C++
friend functions are special functions which can access the private members of a class. They are
considered to be a loophole in the Object Oriented Programming concepts, but logical use of
them can make them useful in certain cases. For instance: when it is not possible to implement
some function, without making private members accessible in them. This situation arises mostly
in case of operator overloading. In the following example, the friend function print is a member
of class TWO and accesses the private data members a and b of class ONE. #include using
namespace std; //Must be known to TWO //before declaration of ONE. class ONE; class TWO {
public: void print(ONE& x); }; class ONE { int a, b; friend void TWO::print(ONE& x); public:
ONE() : a(1), b(2) { } }; void TWO::print(ONE& x) { cout << "a is " << x.a << endl; cout <<
"b is " << x.b << endl; } int main() { ONE xobj; TWO yobj; yobj.print(xobj); } Friend
functions have the following properties: 1) Friend of the class can be member of some other
class. 2) Friend of one class can be friend of another class or all the classes in one program, such
a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members
of the class in which they are declared to be friend, but they can use the members for a specific
object. 4) Friends are non-members hence do not get “this” pointer. 5) Friends, can be friend of
more than one class, hence they can be used for message passing between the classes. 6) Friend
can be declared anywhere (in public, protected or private section) in the class. Friend Class A
class can also be declared to be the friend of some other class. When we create a friend class then
all the member functions of the friend class also become the friend of the other class. This
requires the condition that the friend becoming class must be first declared or defined (forward
declaration). #include using namespace std; class MyClass { // Declare a friend class friend
class SecondClass; public: MyClass() : Secret(0){} void printMember() {
cout << Secret << endl; } private: int Secret; }; class SecondClass { public: void
change( MyClass& yourclass, int x ) { yourclass.Secret = x; } }; void main() {
MyClass my_class; SecondClass sec_class; my_class.printMember(); sec_class.change(
my_class, 5 ); my_class.printMember(); } Note:we declared friend class SecondClass; in the
class MyClass, so we can access Secret in the class SecondClass. Another property of friendships
is that they are not transitive: The friend of a friend is not considered to be a friend unless
explicitly specified. A friend function is used for accessing the non-public members of a class. A
class can allow non-member functions and other classes to access its own private data, by
making them friends. Thus, a friend function is an ordinary function or a member of another
class. A friend class has full access of private data members of another class without being
member of that class.

More Related Content

Similar to Static Keyword Static is a keyword in C++ used to give special chara.pdf

New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variablesSaurav Kumar
 
Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Syed Umair
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptxMrMudassir
 
Java For Automation
Java   For AutomationJava   For Automation
Java For AutomationAbhijeet Dubey
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptxsyedabbas594247
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++Reddhi Basu
 
5.program structure
5.program structure5.program structure
5.program structureShankar Gangaju
 
Notes on c++
Notes on c++Notes on c++
Notes on c++Selvam Edwin
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageJenish Bhavsar
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semKavita Dagar
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4Mahmoud Ouf
 
What's New In Python 2.4
What's New In Python 2.4What's New In Python 2.4
What's New In Python 2.4Richard Jones
 

Similar to Static Keyword Static is a keyword in C++ used to give special chara.pdf (20)

New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Static keyword u.s ass.(2)
Static keyword u.s ass.(2)
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
5.program structure
5.program structure5.program structure
5.program structure
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C Language
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
What's New In Python 2.4
What's New In Python 2.4What's New In Python 2.4
What's New In Python 2.4
 

More from KUNALHARCHANDANI1

The metal will undergo oxidation forming metal ion and releasing .pdf
 The metal will undergo oxidation forming metal ion and releasing .pdf The metal will undergo oxidation forming metal ion and releasing .pdf
The metal will undergo oxidation forming metal ion and releasing .pdfKUNALHARCHANDANI1
 
Sr2+ is most likely to substitute for Ca2+ becaus.pdf
                     Sr2+ is most likely to substitute for Ca2+ becaus.pdf                     Sr2+ is most likely to substitute for Ca2+ becaus.pdf
Sr2+ is most likely to substitute for Ca2+ becaus.pdfKUNALHARCHANDANI1
 
may be that peak id due to presence of alkyl gro.pdf
                     may be that peak id due to presence of  alkyl gro.pdf                     may be that peak id due to presence of  alkyl gro.pdf
may be that peak id due to presence of alkyl gro.pdfKUNALHARCHANDANI1
 
There should only have one singlet resonance for .pdf
                     There should only have one singlet resonance for .pdf                     There should only have one singlet resonance for .pdf
There should only have one singlet resonance for .pdfKUNALHARCHANDANI1
 
the link is not working can u pls write questions.pdf
                     the link is not working can u pls write questions.pdf                     the link is not working can u pls write questions.pdf
the link is not working can u pls write questions.pdfKUNALHARCHANDANI1
 
The one have higher value of E(cell) is acting as.pdf
                     The one have higher value of E(cell) is acting as.pdf                     The one have higher value of E(cell) is acting as.pdf
The one have higher value of E(cell) is acting as.pdfKUNALHARCHANDANI1
 
Nicotine has a molecular formula of C10H14N2 .pdf
                     Nicotine has a molecular formula of C10H14N2     .pdf                     Nicotine has a molecular formula of C10H14N2     .pdf
Nicotine has a molecular formula of C10H14N2 .pdfKUNALHARCHANDANI1
 
HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf
                     HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf                     HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf
HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdfKUNALHARCHANDANI1
 
Which of the following would be a description of a system unitA c.pdf
Which of the following would be a description of a system unitA c.pdfWhich of the following would be a description of a system unitA c.pdf
Which of the following would be a description of a system unitA c.pdfKUNALHARCHANDANI1
 
Water is a polar inorganic solvent. Benzene is a nonpolar organic so.pdf
Water is a polar inorganic solvent. Benzene is a nonpolar organic so.pdfWater is a polar inorganic solvent. Benzene is a nonpolar organic so.pdf
Water is a polar inorganic solvent. Benzene is a nonpolar organic so.pdfKUNALHARCHANDANI1
 
viruses which have single strande DNA in their genome come under cat.pdf
viruses which have single strande DNA in their genome come under cat.pdfviruses which have single strande DNA in their genome come under cat.pdf
viruses which have single strande DNA in their genome come under cat.pdfKUNALHARCHANDANI1
 
This word problem is about a triangle whose perimeter is 47 miles. S.pdf
This word problem is about a triangle whose perimeter is 47 miles. S.pdfThis word problem is about a triangle whose perimeter is 47 miles. S.pdf
This word problem is about a triangle whose perimeter is 47 miles. S.pdfKUNALHARCHANDANI1
 
CH4 + 2O2 -- CO2 + 2H2O note CH4 combustion is.pdf
                     CH4 + 2O2 -- CO2 + 2H2O  note CH4 combustion is.pdf                     CH4 + 2O2 -- CO2 + 2H2O  note CH4 combustion is.pdf
CH4 + 2O2 -- CO2 + 2H2O note CH4 combustion is.pdfKUNALHARCHANDANI1
 
SbAspnSolutionSbAspn.pdf
SbAspnSolutionSbAspn.pdfSbAspnSolutionSbAspn.pdf
SbAspnSolutionSbAspn.pdfKUNALHARCHANDANI1
 
Carbon 2 is where D and L differ for all sugars. .pdf
                     Carbon 2 is where D and L differ for all sugars. .pdf                     Carbon 2 is where D and L differ for all sugars. .pdf
Carbon 2 is where D and L differ for all sugars. .pdfKUNALHARCHANDANI1
 
Program to print the Diamond Shape -#include stdio.h int ma.pdf
Program to print the Diamond Shape -#include stdio.h int ma.pdfProgram to print the Diamond Shape -#include stdio.h int ma.pdf
Program to print the Diamond Shape -#include stdio.h int ma.pdfKUNALHARCHANDANI1
 
Part D option 4 is answerUnless untill they are exposed by some me.pdf
Part D option 4 is answerUnless untill they are exposed by some me.pdfPart D option 4 is answerUnless untill they are exposed by some me.pdf
Part D option 4 is answerUnless untill they are exposed by some me.pdfKUNALHARCHANDANI1
 
Isomers which have their atoms connected in the same sequence but di.pdf
Isomers which have their atoms connected in the same sequence but di.pdfIsomers which have their atoms connected in the same sequence but di.pdf
Isomers which have their atoms connected in the same sequence but di.pdfKUNALHARCHANDANI1
 
import java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdfimport java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdfKUNALHARCHANDANI1
 

More from KUNALHARCHANDANI1 (20)

The metal will undergo oxidation forming metal ion and releasing .pdf
 The metal will undergo oxidation forming metal ion and releasing .pdf The metal will undergo oxidation forming metal ion and releasing .pdf
The metal will undergo oxidation forming metal ion and releasing .pdf
 
Sr2+ is most likely to substitute for Ca2+ becaus.pdf
                     Sr2+ is most likely to substitute for Ca2+ becaus.pdf                     Sr2+ is most likely to substitute for Ca2+ becaus.pdf
Sr2+ is most likely to substitute for Ca2+ becaus.pdf
 
may be that peak id due to presence of alkyl gro.pdf
                     may be that peak id due to presence of  alkyl gro.pdf                     may be that peak id due to presence of  alkyl gro.pdf
may be that peak id due to presence of alkyl gro.pdf
 
There should only have one singlet resonance for .pdf
                     There should only have one singlet resonance for .pdf                     There should only have one singlet resonance for .pdf
There should only have one singlet resonance for .pdf
 
the link is not working can u pls write questions.pdf
                     the link is not working can u pls write questions.pdf                     the link is not working can u pls write questions.pdf
the link is not working can u pls write questions.pdf
 
The one have higher value of E(cell) is acting as.pdf
                     The one have higher value of E(cell) is acting as.pdf                     The one have higher value of E(cell) is acting as.pdf
The one have higher value of E(cell) is acting as.pdf
 
Nicotine has a molecular formula of C10H14N2 .pdf
                     Nicotine has a molecular formula of C10H14N2     .pdf                     Nicotine has a molecular formula of C10H14N2     .pdf
Nicotine has a molecular formula of C10H14N2 .pdf
 
i have it .pdf
                     i have it                                      .pdf                     i have it                                      .pdf
i have it .pdf
 
HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf
                     HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf                     HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf
HClO4 in aqueous medium ionizes as Hydrogen(+1)ca.pdf
 
Which of the following would be a description of a system unitA c.pdf
Which of the following would be a description of a system unitA c.pdfWhich of the following would be a description of a system unitA c.pdf
Which of the following would be a description of a system unitA c.pdf
 
Water is a polar inorganic solvent. Benzene is a nonpolar organic so.pdf
Water is a polar inorganic solvent. Benzene is a nonpolar organic so.pdfWater is a polar inorganic solvent. Benzene is a nonpolar organic so.pdf
Water is a polar inorganic solvent. Benzene is a nonpolar organic so.pdf
 
viruses which have single strande DNA in their genome come under cat.pdf
viruses which have single strande DNA in their genome come under cat.pdfviruses which have single strande DNA in their genome come under cat.pdf
viruses which have single strande DNA in their genome come under cat.pdf
 
This word problem is about a triangle whose perimeter is 47 miles. S.pdf
This word problem is about a triangle whose perimeter is 47 miles. S.pdfThis word problem is about a triangle whose perimeter is 47 miles. S.pdf
This word problem is about a triangle whose perimeter is 47 miles. S.pdf
 
CH4 + 2O2 -- CO2 + 2H2O note CH4 combustion is.pdf
                     CH4 + 2O2 -- CO2 + 2H2O  note CH4 combustion is.pdf                     CH4 + 2O2 -- CO2 + 2H2O  note CH4 combustion is.pdf
CH4 + 2O2 -- CO2 + 2H2O note CH4 combustion is.pdf
 
SbAspnSolutionSbAspn.pdf
SbAspnSolutionSbAspn.pdfSbAspnSolutionSbAspn.pdf
SbAspnSolutionSbAspn.pdf
 
Carbon 2 is where D and L differ for all sugars. .pdf
                     Carbon 2 is where D and L differ for all sugars. .pdf                     Carbon 2 is where D and L differ for all sugars. .pdf
Carbon 2 is where D and L differ for all sugars. .pdf
 
Program to print the Diamond Shape -#include stdio.h int ma.pdf
Program to print the Diamond Shape -#include stdio.h int ma.pdfProgram to print the Diamond Shape -#include stdio.h int ma.pdf
Program to print the Diamond Shape -#include stdio.h int ma.pdf
 
Part D option 4 is answerUnless untill they are exposed by some me.pdf
Part D option 4 is answerUnless untill they are exposed by some me.pdfPart D option 4 is answerUnless untill they are exposed by some me.pdf
Part D option 4 is answerUnless untill they are exposed by some me.pdf
 
Isomers which have their atoms connected in the same sequence but di.pdf
Isomers which have their atoms connected in the same sequence but di.pdfIsomers which have their atoms connected in the same sequence but di.pdf
Isomers which have their atoms connected in the same sequence but di.pdf
 
import java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdfimport java.util.Scanner;import java.text.DecimalFormat;import j.pdf
import java.util.Scanner;import java.text.DecimalFormat;import j.pdf
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1
 

Static Keyword Static is a keyword in C++ used to give special chara.pdf

  • 1. Static Keyword 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, Static variable in functions Static Class Objects Static member Variable in class Static Methods in class 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(0 { for(int i=0;i<5;i++) { counter(); } } Output : 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(); } } Output : 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 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. Assignment to zero, on using static keyword is only for primitive datatypes, not for user defined datatypes. 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 destructor not called upon the end of the scope of if condition. This is because object was static, which has scope till the program lifetime, hence destructor for this object was called when main() exits. Static data member in class Static data members of class are those members which are shared by all the objects. Static data member has a single piece of storage, and is not available as separate copy with each object, like other non- static data members. Static member variables (data members) are not initialied using constructor, because these are not dependent on object initialization. Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error. class X { static int i; public: X(){}; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i } Once the definition for static data member is made, user cannot redefine it. Though, arithmetic operations can be performed on it. Static Member Functions These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator. Example : class X { public: static void f(){}; }; int main() { X::f(); // calling member function directly with class name } These functions cannot access ordinary data members and member functions, but only static data members and static member
  • 2. functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study about "this" keyword later. n the lesson on file scope and the static keyword, you learned that static variables keep their values and are not destroyed even after they go out of scope. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include int generateID() { static int s_id = 0; return ++s_id; } int main() { std::cout << generateID() << ' '; std::cout << generateID() << ' '; std::cout << generateID() << ' '; return 0; } This program prints: 1 2 3 Note that s_id has kept its value across multiple function calls. The static keyword has another meaning when applied to global variables -- it gives them internal linkage (which restricts them from being seen/used outside of the file they are defined in). Because global variables are typically avoided, the static keyword is not often used in this capacity. Static member variables C++ introduces two more uses for the static keyword when applied to classes: static member variables, and static member functions. Fortunately, these uses are fairly straightforward. We’ll talk about static member variables in this lesson, and static member functions in the next. Before we go into the static keyword as applied to member variables, first consider the following class: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Something { public: int m_value = 1; }; int main() { Something first; Something second; second.m_value = 2; std::cout << first.m_value << ' '; std::cout << second.m_value << ' '; return 0; } When we instantiate a class object, each object gets its own copy of all normal member variables. In this case, because we have declared two Something class objects, we end up with two copies of m_value: first.m_value, and second.m_value. first.m_value is distinct from second.m_value. Consequently, the program above prints: 1 2 Member variables of a class can be made static by using the static keyword. Unlike normal member variables, static member variables are shared by all objects of the class. Consider the following program, similar to the above: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Something { public: static int s_value; }; int Something::s_value = 1; int main() { Something first; Something second; second.s_value = 2; std::cout << first.s_value << ' '; std::cout << second.s_value << ' '; return 0; } This program produces the following output: 2 2 Because s_value is a static member variable, s_value is shared between all objects of the class. Consequently, first.s_value is the same variable as second.s_value. The above program shows that the value we set using first can be accessed using second! if static or global, indeterminate if storage class is auto C has always been very specific about the initial values of objects. If global or static, they will be zeroed. If auto, the value is indeterminate. This was the case in pre-C89 compilers and was so specified by K&R and in DMR's original C report. This was the case in C89, see section 6.5.7 Initialization. If an object that has automatic storage duration is not initialized explicitely, its value is indeterminate. If an object that has static storage duration is not initialized explicitely, it is initialized implicitely as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
  • 3. This was the case in C99, see section 6.7.8 Initialization. If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a null pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules; — if it is a union, the first named member is initialized (recursively) according to these rules. As to what exactly indeterminate means, I'm not sure for C89, C99 says: indeterminate value either an unspecified value or a trap representation But regardless of what standards say, in real life, each stack page actually does start off as zero, but when your program looks at any auto storage class values, it sees whatever was left behind by your own program when it last used those stack addresses. If you allocate a lot of auto arrays you will see them eventually start neatly with zeroes. n general, what doesn't change with something that is static in a programming language is whether it is alive or not. Static variables are always alive; they have a single instance which comes into being either at the beginning of the program or the first time they are visible, and lasts until the end of the program. Non-static variables come and go, as blocks are entered and left, or as class instances are created and destroyed. In C++, for reasons of C compatibility, static, when applied to variables at namespace scope, has a completely unrelated meaning: it means that the variable has internal, rather than external linkage, and is not visible in other translation units. Why the word static was adopted for this in early C, I don't know; I can only guess that they needed something, and didn't want to introduce a new keyword. (Originally, in the very earliest versions of C, variables at file scope obeyed the rules of a Fortran named common block: all variables of the same name referred to the same storage.) Looking back, of course (with 20/20 hindsight), the default for variables at file scope should have been internal linkage, with a special keyword (public?) to say that the variable had external linkage. But this was a lot less obvious in the early 1970's. 2 down vote Static is referred to the variable storage. Inside a function call, every variable that you declare is pushed on the stack. Unlike other variables, a static variable isn't pushed on the stack, it's like a global variable, that survives the whole execution of the program, with the difference that is visible only inside the block is declared. Friend Functions A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading. In the following example, the friend function print is a member of class TWO and accesses the private data members a and b of class ONE. #include using namespace std; //Must be known to TWO //before declaration of ONE. class ONE; class TWO { public: void print(ONE& x); }; class ONE { int a, b; friend void TWO::print(ONE& x); public:
  • 4. ONE() : a(1), b(2) { } }; void TWO::print(ONE& x) { cout << "a is " << x.a << endl; cout << "b is " << x.b << endl; } int main() { ONE xobj; TWO yobj; yobj.print(xobj); } Friend functions have the following properties: 1) Friend of the class can be member of some other class. 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object. 4) Friends are non-members hence do not get “this” pointer. 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes. 6) Friend can be declared anywhere (in public, protected or private section) in the class. Friend Class A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration). #include using namespace std; class MyClass { // Declare a friend class friend class SecondClass; public: MyClass() : Secret(0){} void printMember() { cout << Secret << endl; } private: int Secret; }; class SecondClass { public: void change( MyClass& yourclass, int x ) { yourclass.Secret = x; } }; void main() { MyClass my_class; SecondClass sec_class; my_class.printMember(); sec_class.change( my_class, 5 ); my_class.printMember(); } Note:we declared friend class SecondClass; in the class MyClass, so we can access Secret in the class SecondClass. Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified. A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. A friend class has full access of private data members of another class without being member of that class. Solution Static Keyword 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, Static variable in functions Static Class Objects Static member Variable in class Static Methods in class 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(0 { for(int i=0;i<5;i++) { counter(); } } Output : 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
  • 5. { for(int i=0;i<5;i++) { counter(); } } Output : 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 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. Assignment to zero, on using static keyword is only for primitive datatypes, not for user defined datatypes. 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 destructor not called upon the end of the scope of if condition. This is because object was static, which has scope till the program lifetime, hence destructor for this object was called when main() exits. Static data member in class Static data members of class are those members which are shared by all the objects. Static data member has a single piece of storage, and is not available as separate copy with each object, like other non- static data members. Static member variables (data members) are not initialied using constructor, because these are not dependent on object initialization. Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error. class X { static int i; public: X(){}; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i } Once the definition for static data member is made, user cannot redefine it. Though, arithmetic operations can be performed on it. Static Member Functions These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator. Example : class X { public: static void f(){}; }; int main() { X::f(); // calling member function directly with class name } These functions cannot access ordinary data members and member functions, but only static data members and static member functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study about "this" keyword later. n the lesson on file scope and the static keyword, you learned that static variables keep their values and are not destroyed even after they go out of scope. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include int generateID() { static int s_id = 0; return ++s_id; } int main() { std::cout << generateID() << ' '; std::cout << generateID() << ' '; std::cout << generateID() << ' '; return 0; } This program prints: 1 2 3 Note that s_id has kept its value across multiple function calls. The static keyword has another meaning when applied to global variables -- it gives them internal linkage (which restricts them from being seen/used outside of the file they are defined in). Because global variables are
  • 6. typically avoided, the static keyword is not often used in this capacity. Static member variables C++ introduces two more uses for the static keyword when applied to classes: static member variables, and static member functions. Fortunately, these uses are fairly straightforward. We’ll talk about static member variables in this lesson, and static member functions in the next. Before we go into the static keyword as applied to member variables, first consider the following class: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Something { public: int m_value = 1; }; int main() { Something first; Something second; second.m_value = 2; std::cout << first.m_value << ' '; std::cout << second.m_value << ' '; return 0; } When we instantiate a class object, each object gets its own copy of all normal member variables. In this case, because we have declared two Something class objects, we end up with two copies of m_value: first.m_value, and second.m_value. first.m_value is distinct from second.m_value. Consequently, the program above prints: 1 2 Member variables of a class can be made static by using the static keyword. Unlike normal member variables, static member variables are shared by all objects of the class. Consider the following program, similar to the above: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Something { public: static int s_value; }; int Something::s_value = 1; int main() { Something first; Something second; second.s_value = 2; std::cout << first.s_value << ' '; std::cout << second.s_value << ' '; return 0; } This program produces the following output: 2 2 Because s_value is a static member variable, s_value is shared between all objects of the class. Consequently, first.s_value is the same variable as second.s_value. The above program shows that the value we set using first can be accessed using second! if static or global, indeterminate if storage class is auto C has always been very specific about the initial values of objects. If global or static, they will be zeroed. If auto, the value is indeterminate. This was the case in pre-C89 compilers and was so specified by K&R and in DMR's original C report. This was the case in C89, see section 6.5.7 Initialization. If an object that has automatic storage duration is not initialized explicitely, its value is indeterminate. If an object that has static storage duration is not initialized explicitely, it is initialized implicitely as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant. This was the case in C99, see section 6.7.8 Initialization. If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a null pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules; — if it is a union, the first named member is initialized (recursively) according to these rules. As to what exactly indeterminate means, I'm not sure for C89, C99 says: indeterminate value either an unspecified value or a trap representation But regardless of what standards say, in real life, each stack page actually does start off as zero, but when your program looks at any auto storage class values, it
  • 7. sees whatever was left behind by your own program when it last used those stack addresses. If you allocate a lot of auto arrays you will see them eventually start neatly with zeroes. n general, what doesn't change with something that is static in a programming language is whether it is alive or not. Static variables are always alive; they have a single instance which comes into being either at the beginning of the program or the first time they are visible, and lasts until the end of the program. Non-static variables come and go, as blocks are entered and left, or as class instances are created and destroyed. In C++, for reasons of C compatibility, static, when applied to variables at namespace scope, has a completely unrelated meaning: it means that the variable has internal, rather than external linkage, and is not visible in other translation units. Why the word static was adopted for this in early C, I don't know; I can only guess that they needed something, and didn't want to introduce a new keyword. (Originally, in the very earliest versions of C, variables at file scope obeyed the rules of a Fortran named common block: all variables of the same name referred to the same storage.) Looking back, of course (with 20/20 hindsight), the default for variables at file scope should have been internal linkage, with a special keyword (public?) to say that the variable had external linkage. But this was a lot less obvious in the early 1970's. 2 down vote Static is referred to the variable storage. Inside a function call, every variable that you declare is pushed on the stack. Unlike other variables, a static variable isn't pushed on the stack, it's like a global variable, that survives the whole execution of the program, with the difference that is visible only inside the block is declared. Friend Functions A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading. In the following example, the friend function print is a member of class TWO and accesses the private data members a and b of class ONE. #include using namespace std; //Must be known to TWO //before declaration of ONE. class ONE; class TWO { public: void print(ONE& x); }; class ONE { int a, b; friend void TWO::print(ONE& x); public: ONE() : a(1), b(2) { } }; void TWO::print(ONE& x) { cout << "a is " << x.a << endl; cout << "b is " << x.b << endl; } int main() { ONE xobj; TWO yobj; yobj.print(xobj); } Friend functions have the following properties: 1) Friend of the class can be member of some other class. 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object. 4) Friends are non-members hence do not get “this” pointer. 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes. 6) Friend can be declared anywhere (in public, protected or private section) in the class. Friend Class A
  • 8. class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration). #include using namespace std; class MyClass { // Declare a friend class friend class SecondClass; public: MyClass() : Secret(0){} void printMember() { cout << Secret << endl; } private: int Secret; }; class SecondClass { public: void change( MyClass& yourclass, int x ) { yourclass.Secret = x; } }; void main() { MyClass my_class; SecondClass sec_class; my_class.printMember(); sec_class.change( my_class, 5 ); my_class.printMember(); } Note:we declared friend class SecondClass; in the class MyClass, so we can access Secret in the class SecondClass. Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified. A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. A friend class has full access of private data members of another class without being member of that class.