Tuesday, October 9, 2018

static keyword in C++

Static keyword description:-

A static keyword can be applied with member variable as well as member function of the class. If we define a variable is static then that variable will be global that means variable will be the part of class not of the object. Memory allocation for the static variable will be done by only once. Static variable will be shareable to each and every object and its memory will be allocated only once at the time of class creation. 

The variable and the function which are the part of the object is called instance variable. Static variable is called class variable. If we do not provide the initial value to the  object variable then it will take garbage value and static variable  will take default values. 

How to make a variable static:-

We can make a variable as a static by simply write keyword static before variable name. There are necessary condition to define that variable outside the class.

Data type of variable  Class-name:: variable-name;

we can also initialize by our own value to here by code

Data type of variable Class-name:: variable-name value;

#include <iostream>
#include<conio.h>
using namespace std;
class pramod
{
    public:
        int a;          //if don't initialize instance variable then it will
        static int b;                //take garbage value(Any value defined by compiler)
        void add(void);
};
int pramod::b;
void pramod::add()
{
    cout<<a<<endl;
    cout<<pramod::b;
}
int main()
{
    pramod ab;
    ab.add();
    return 0;
}

  Static Function:-

If we write static keyword before member function then that function will be the static function.

Necessary Condition for function:-

1. If a variable is static then it may or may not written in static function.

2. If a function is static then it must contain only static variable.

3. A static variable or a static function will be called by class name but it can be called by object name also.

#include <iostream>
#include<conio.h>
using namespace std;
class pramod
{
    public:
        int a;
        static int b;
        void add(void);
        static void add1()
        {
            //cout<<a;   //we can not write non static variable in static
            cout<<b<<endl;
        }
};
int pramod::b;
void pramod::add()
{
    b++;         //retain its previous values.
    cout<<b<<endl;//static variable is written in non static function.
}
int main()
{
    pramod ab;
    ab.add();
    ab.add();
    pramod::add1();
    cout<<ab.b;  //call static variable by object name no problem
    return 0;
}



 

Font and Basefont tag of html in a very easy way.

Difference between font and basefont tag in html:- Font tag is a container tag. Basefont tag is empty tag. We can apply font tag in a ...