I don't understand why the memory address of "*x" inside "Product destructor" doesn't equal to 30 but a number series 2379648

#include<iostream>
#include<string>
using namespace std;

class product {
int *x,*y;
public:

product (int c,int d);
int area(){return *(x)* (*y);}
~product ();
};
product::product(int a, int b)
{
y=&b;
x=&a;
*y=b;
*x=a;
cout<<"\n"<<*x<<"\n"<<*y<<endl;
cout<<"\n"<<x<<"\n"<<y<<endl;
}
product::~product ()
{
cout<<"\ndelete"<<"\n"<<*x<<"\n"<<*y<<endl;
cout<<"\ndelete"<<"\n"<<x<<"\n"<<y<<endl;

}
int main ()
{
int b=19;
int a=30;
string buf[10];
//cout<<"Enter First Numbers for Multiplication:";
// cin>>a;
// cout<<"Enter Second Numbers for Multiplication:";
// cin>>b;
product product(a,b);
cout<<"area:"<<"\n"<<product.area();
cout<<"area:"<<"\n"<<&buf[product.area()];

}
In the constructor, you are taking the address of temporary parameters a and b, not the a and b in main(). Try taking the parameters by reference, or simply taking pointers directly.
But why would *y equal to 19 by not using reference?
You got lucky. You're invoking undefined behavior by dereferencing a pointer to memory that no longer exists, so anything could happen, including seeing the value you set there still being there. It may also not be there (instead being garbage, as you noticed with x), or even crash.
I got it. Thanks a lot. !!!!!!!
Topic archived. No new replies allowed.