Class problem

• 03-26-2006
w274v
Class problem
I have a program that should take some points that make a straight line and calculate a slope. I am getting some random garbage and I don't know why.

I have a class "Line":
Code:

```class Line  {       private:         Point p1;         Point p2;         double slope;         double yInt;       public:                 Point readPts(Point p1, Point p2);                 void slopePts(Point p1, Point p2); }```
and a class "Point":
Code:

```class Point {       private:               double dX;               double dY;       public:               friend class Line; };```
In my Line.cpp file, I have:
Code:

```Point Line::readPts(Point p1, Point p2) {       cout <<"Enter the point's X coordinate: ";       cin >> p1.dX;       cout <<"And its Y coordinate: ";       cin >> p1.dY;       cout <<"Enter the point's X coordinate: ";       cin >> p2.dX;       cout <<"And its Y coordinate: ";       cin >> p2.dY; } void Line::slopePts(Point p1, Point p2) {     slope = (p2.dY - p1.dY) / (p2.dX - p1.dX); }```
In my main.cpp, here is where I call the function to read in points:
Code:

```Line AB, BC; AB.readPts(p1, p2); //reading in points for line AB CD.readPts(p1, p2); //reading in points for line CD```

If I print "p1.dX" or "p1.dY" etc. in the "readPts" function, obviously the correctly entered numbers will come out. However, when I print these in the "slopePts" function, they will be garbage. This is why my slope is comming out as garbage as well.
• 03-26-2006
Daved
You are passing the points by value to the readPts function, so that function is getting a copy and reading data into that copy. The original variables p1 and p2 in main.cpp never change and are probably just un-initialized.

You could pass the points by reference to the function, or you could make the read function a member of the Point class, or what probably makes the most sense is to remove the function parameters completely and read into the member variables of the Line class.
• 03-26-2006
theJ89
dX and dY are private, don't they have to be protected for other classes to reference them via the friend statement?