I am having a hard time understanding how to fix this code I get the error message that both point Point::x & Point::y are inaccessible. How do I fix this?
class Point {
int x, y;
public:
Point(int u, int v) : x(u), y(v) {}
int getX() { return x; }
int getY() { return y; }
void setX(int newX) { x = newX; }
void setY(int newY) { y= newY; }
};
int main() {
Point p(5, 3);
std::cout << p.x << ' ' << p.y;//should print out 5 3
return 0;
}
CodePudding user response:
The problem is that the data members x and y are private by default for a class type defined using the keyword class(as opposed to keyword struct).
To solve the error you can use the getters getX and getY as shown below:
std::cout << p.getX() << ' ' << p.getY();
Demo.
Another option(less/not recommended) would be to make x and y public or use struct keyword but that would defeat the purpose of having getters and setters(setX and setY).
CodePudding user response:
Class members (as opposed to struct members) are private by default so you can't directly access Point::x and Point::y outside of the definition of Point; however, you have defined getters for those values which are public.
