
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.

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 uninitialized.
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.

dX and dY are private, don't they have to be protected for other classes to reference them via the friend statement?
Point Line::readPts(Point p1, Point p2)
Also notice that function doesn't return a point.
These two variables could be replaced with functions that retrieve the slope and yInt instead of storing them in memory:
double slope;
double yInt;

No, a friend is allowed access to a class's privates.