// file 1
static int x;
static void foo(){
std::cout<<"hi\\n"<<std::endl;
}
static keyword makes the variable/function visible only to the members of the same c++ file this avoids collisions during linking. Unless we want a function or a variable to be linked externally we will should declare it as static.
On the other hand if we want a variable to be resolved externally we use extern keyword
extern int y; // will look for y in other files
A Static Variable for a class is a common variable for the entire class and is the same for all instances of the class.
class hi{
public:
static int x;
};
// int hi::x;
void solve(){
hi h;
cout<<h.x<<endl;
}
class hi{
public:
static int x;
};
int hi::x = 11;
void solve(){
hi h1,h2;
h1.x = -1;
cout<<h1.x<<endl;
cout<<h2.x<<endl;
// output-> -1 , -1
}
A static method much like the static variable belongs to class the rather than the object and can be called as ClassName::method() and hence it has no access to this→ pointer and also non static members of the class!
class MyClass {
public:
static int staticVar;
static void staticMethod() {
cout << staticVar << endl;
}
};
int MyClass::staticVar = 10;
Class functions basically get a hidden parameter which contains the data of the class while static methods don’t
struct Color : int{
WHITE = 0,
GRAY, // = 1
BLACK // =2
};
struct Type : unsigned char{
WHITE = 5,
GRAY, // = 6
BLACK // = 7
};
class Hello{
int x , y , z;
public:
Hello() : x(0) , y(0) , z(0) {
//constructor works
}
};
class Example{
public:
Example(){
cout<<"bann gaya with default"<<'\\n';
}
Example(int y){
cout<<"bann gaya with " << y <<'\\n';
}
}
class Entity{
private:
Example e1;
public:
/* Entity(){
e1 = Example(8); // twice the constructor will be called
} */
Entity(): e1(Example(8)){ // constructor called only once
}
}