int main ()
{
data.x = 1; // x error because its non static
return 0;
}
Code 2
#include <iostream>
using namespace std;
class data
{
public:
static int x; // i fix the error by giving x static, but dont understand why it does that, but it works
}
int main ()
{
data.x = 1;
return 0;
}
Code 3
#include <iostream>
using namespace std;
class data
{
public:
int x;
}
int main ()
{
data data1; // here i fix the error, still dont understand why this work to
data1.x = 1;
return 0;
}
So, my problem is. In Code 1 i have a syntax error that is x is non-static. In code 1 i fix the error by giving the x variable in the class as static. And in code three i fix the error by doing data data1; (i don't know what this is called). So, my problem is that i don't know exactly why the error in code 1 occur? And what is the benefit of doing code 2 and code 3? And is there a better way? And if you could, please give me a reference to read.
In Code 1 you're trying to use a variable of a class, which is impossible, because classes don't have "physical" variables, only Objects do.
In Code 3, you (correctly) instantiated an Object (data1) of your class (data). data1 does have variables, because it is an object.
For proper understanding, take this example:
Every "Person" has a "name". That means your.name = radit91 and my.name = Gaminic, because we are both Persons. What you're trying to do in Code 1 is call Person.name, which is meaningless, as the abstract "Person" doesn't have a name.
In Code 2 you made your variable "static", which means it's shared by all Objects of that class. Generally, this is not what you want, and when you do, you'll be back to ask "How do I do this?" and we'll answer "Use static variables". Until that day, feel free to ignore the "static" keyword.
Class actually doesnt exist in memory.
When you did data data1; you made an OBJECT named data1 of a CLASS data. Object actually exists.
In code 1 you dont need to make object beacuse static var in classes is common for all objects of that class.