Static
Static
}
};
int GfG::i = 1;
int main()
{
GfG obj;
cout <<obj.i;
return 0;
}
Class objects as static:
• Just like variables, objects also when declared as static
have a scope till the lifetime of program.
• If the object is declared inside the if block as non-
static.
• So, the scope of variable is inside the if block only.
• So when the object is created the constructor is
invoked and soon as the control of if block gets over
the destructor is invoked as the scope of object is
inside the if block only where it is declared.
#include<iostream>
using namespace std;
class GfG
{
int i = 0;
public:
GfG()
{
i = 0;
cout << "Inside Constructor\n";
}
~GfG()
{
cout << "Inside Destructor\n";
}
};
int main()
{
int x = 0;
if (x==0)
{
static GfG obj;
}
cout << "End of main\n";
}
output
Inside Constructor
End of main
Inside Destructor
Static functions in a class
• Just like the static data members or static variables inside the
class, static member functions also does not depend on
object of class.
• It is recommended to invoke the static members using the
class name and the scope resolution operator.
• Static member functions are allowed to access only the static
data members or other static member functions, they can
not access the non-static data members or member
functions of the class.
#include<iostream>
using namespace std;
class GfG
{
public:
static void printMsg()
{
cout<<"Welcome to GfG!";
}
};
int main()
{
// invoking a static member function
GfG::printMsg();
}
Output
#include<iostream>
using namespace std;
class Test
{
static int i;
int j;
};
int main()
{
cout << sizeof(Test);
return 0;
}
Output: 4 (size of integer)
static data members do not contribute in size of
an object. So ‘i’ is not considered in size of Test.
Also, all functions (static and non-static both) do
not contribute in size.