When we declare variables in a class and then when we assign the value of those variables, for example like this
class c {
public :
int x;
int x2;
c () {
x = 0;
x2 = 0;
scanf ("%d", &x); and now we're gonna input for example 10
}
};
each time the class is used, I mean each time the constructor is called, the value of x becomes 0 again since it is initialized as zero in the constructor. However if we don’t initialize the value, there will be errors.
My question is that how can we keep the value of the variable when we call the constructor again and again so that it doesn’t become zero ?
Edit:
void example () {
int i;
scanf ("%d", &i);
switch (i) {
case 1 : {Object ob1; system ("cls"); menu ();} // this object contains a value like 20
case 2 : {Object ob2; system ("cls"); menu ();}
}
}
There is another switch case in Object 1 which includes an option to go back to a main menu, now if I enter 1 again go back to object 1 I cannot see the value 20, it will be 0
Do you understand the difference between classes and objects/instances? Classes are merely a “Cookie-cutter” for objects. You don’t “call” a constructor as such, but you create an instance of your class (which implicitely calls the constructor):
This code will create two instances of class c, both with their own version of x1 and x2. It’s true that the constructor is run a second time when creating
anotherObj, but it operates on totally different memory. So the values of x1 and x2 inmyObjwon’t be touched.Edit: The point of class member functions is that they operate on an implicit additional parameter named this. You could imagine that the “constructor call” actually looks like that (Just for illustrative purposes, not meant to be valid code):
That can also be achieved in C – but in C++, it happens implicitly, without you having to write code like this. You just write
c newObj;orc* obj = new c;.Apart from that: Member variables should be privat, and your mixing C library code (
scanf) with C++ classes – useiostreamsfor input/output in C++.