class definition operation sequence

Hi everyone,
I have a problem with use of pointers in classes.
I defined a class named point as follows

#include<iostream>
using namespace std;

class Point
{
int *x,*y;
public:
Point(int,int);
~Point();
void set_points(int a,int b);
int area()
{
return(*x**y);
}
};


void Point::set_points(int a, int b)
{
x=new int;
y=new int;
*x=a;
*y=b;
}


Point::Point(int a=0,int b=0)
{
x=new int;
y=new int;
*x=a;
*y=b;
}

Point::~Point()
{
delete x;
delete y;
}


// main file

#include<C:\Rohit\examples\point.h>
#include<iostream>
using namespace std;

int main()
{
Point a(4,5);
Point b(6,7);

Point *c;

//a.set_points(4,5);
c->set_points(7,9);

cout << "area of a= " << a.area() << endl;
cout << "area of b= " << b.area() << endl;
cout<< "hello" << endl;
cout << "area of c= " << c->area() << endl;
return 0;
}


In the main file when I comment the c pointer and its related lines the output is correct i.e 20 and 42. However when it is uncommented output for both b and c is correct but the output for a is a random number.I am unable to track the sequence of operations.Could U please help.

Thanks
Okay, first off, I hope that is just for exercise, because under ordinary circumstances, allocating x and y dynamically is a horrible, horrible idea.

Aside from that, here:
Point *c;
c->set_points(7,9);

you create an uninitialized pointer c that doesn't point to anything valid.
Thus, dereferencing c in the next line results in undefined behavior.

You either can do this:
Point c;
c.set_points(7,9);


or if you want to allocate the Point object dynamically too (again, there is no reason to do so in this case either):
1
2
3
4
Point* c=new Point();
c->set_points(7,9);
[...]
delete c;


And set_points leaks memory, because it unnecessarily creates another two int instances (and without deleting the old ones), instead of just reassigning the values.
Topic archived. No new replies allowed.