I have a problem in c++ I am trying to do a simple calculation using OOP but the result is wrong and not close to what it should be:
#include <iostream>
using namespace std;
class productos{
public:
productos(int x,int y){
x=n;
y=m;
cout<<x*y;
}
int producto1(){
return n*m;//Usando esta funcion tampoco arroja el resultado
}
private:
int m;
int n;
int mil;
};
int main()
{
productos dos(2,2500);
return 0;
}
The result is:
-1074975852-1074975852
It also gave me an error initializing:
int m=2500;
I am a beginner in c++ and I have other practically identical console programs, maybe with more functions but basically the same.
What did I do wrong? and how do i fix it?
PS: I already tried with sublime text codeblocks and an online compiler and the result is the same.
Problem with uninitialized variables
You are making a very common mistake and that is to make use of a variable without having been previously set to a value.
As you can see here you are assigning y to the values of
x
and , overriding the values you have passed to the constructor, but these have no values initially, so their initial content is indeterminate.y
n
m
Solution making correct use of the class
If I reorder the code to do what you want, this would be the result:
The result of the execution is:
Error analysis with valgrind
Valgrind results from your code:
Where I highlight the meaning of:
Results of valgrind after correcting the problem:
The problem is in the assignment inside
productos(int x, int y)
since you are assigning to these variables inside the function, maybe you reversed the order of the variables; you have 2 options:productos(int n; int m)
n = x
ym = y
and printcout<<n*m
I did it with way 1:
The values it was throwing at you
-1074975852-1074975852
is because it was taking values from memory when you were doing assignmentsx = n
and n had no value.To avoid variable initialization errors, which I am not going to detail because you already have other answers in which they comment on the problem, it is preferable to initialize all the member variables that is possible in the initialization section within the constructor, let me explain:
Why? Two basic reasons:
In the case of initializing classes you avoid redundant operations:
As a general rule, avoid silly mistakes: