Reputation: 53
I have the following code:
class Point{
private:
double x, y;
public:
Point(){
this->x = 0;
this->y = 0;
}
//...
};
I am getting an error on the private declaration of doubles x and y:
'double Point::y' is private
My code works fine when I rearrange it as:
class Point{
//private:
public:
double x, y;
//public:
Point(){
this->x = 0;
this->y = 0;
}
//...
};
But obviously then double isn't private. If no private keyword is given and the doubles are declared before the public keyword, I get the same private variable error.
What am I doing wrong / how can I declare private variables properly? Thanks!
I have error makers in eclipse both within the class and at the declaration of the doubles: (I placed an X in the code since I can't post screen shots)
class Point{
private:
//public:
X double x, y;
X Point(): x{0},y{0}{
}
SOLVED: Thanks to Dieter Lücking for point out that in my example I forgot to uncomment the public keyword when I provided a full code example. Further along in my code I had written:
cout << "\nPoint sum: " << e.x + e.getY();
This, oddly, caused errors to appear both on the cout line, as well as the declaration line, which is what caused my confusion. Fixing the cout line:
cout << "\nPoint sum: " << e.x + e.getY();
Solved all the errors. Thank you all!
Upvotes: 0
Views: 4560
Reputation: 2985
In the function templateTestSum()
you are accessing the private members x
and y
of point
:
cout << "\nPoint sum: " << e.x + e.y;
This is not allowed.
Upvotes: 0
Reputation: 4746
The most important thing to notice is that in your main
function you try to access x
and y
directly instead of using the accessor functions getX()
and getY()
.
Another thing is that (probably due to recent editing) all of your member functions in Point
are private
. Just uncomment the //public:
line directly before the c'tor.
Upvotes: 2
Reputation: 145459
The code shown at the time of writing this answer isn't the problem.
The compiler complains about some other code accessing private
members of a Point
instance.
For a simple Point
class, with no special class invariant, making the members public is a good idea, but note that in general it's not a good idea.
Since you have x and y members of type double
, note that at least some not-very-long-ago version of Visual C++ had problems optimizing expressions involving such values accessed via accessor methods in a derived class. I don't know why. But it's an addition practical reason to make those members public.
Upvotes: 1