This program gives a garbage value to the variable calc
.
Can anyone help me? What is the problem here?
Code:
#include <iostream>
using namespace std;
class trial {
public:
int m1;
int m2;
int calc = m1 m2;
void setdata(int a1, int a2) {
m1 = a1;
m2 = a2;
}
void getcalc(){
cout << "Sum of m1 & m2 is " << calc << endl;
}
};
int main() {
trial t1;
t1.setdata(3, 8);
t1.getcalc();
system("pause>0");
return 0;
}
Output:
Sum of m1 & m2 is -1717986920
CodePudding user response:
The problem is how you defined calc
.
When a object trial
is initialized, m1 m2
is assigned to calc
, but m1
and m2
are not initialized themselves (they contain 'garbage').
When setdata()
is called, two user-provided integers are assigned to m1
and m2
, but calc
is unchanged, thus the 'garbage' in the output.
You need to update calc
by adding calc = m1 m2;
in setdata()
.
CodePudding user response:
You are never calculating the sum at first place ...
void setdata(int a1, int a2) {
m1 = a1;
m2 = a2;
calc = m1 m2;
}
but always initialize the member variables, you are not initializing the m1 and m2, hence garbage values which is assigned by the compiler.