I have been trying to learn C++ for some time now. Recently I came across the following piece of code:
#include <iostream>
using namespace std;
class Point {
private:
double x_, y_;
public:
Point(double x, double y){
x_ = x;
y_ = y;
}
Point() {
x_ = 0.0;
y_ = 0.0;
}
double getX(){
return x_;
}
double getY(){
return y_;
}
void setX(double x){
x_ = x;
}
void setY(double y){
y_ = y;
}
void add(Point p){
x_ += p.x_;
y_ += p.y_;
}
void sub(Point p){
x_ -= p.x_;
y_ -= p.y_;
}
void mul(double a){
x_ *= a;
y_ *= a;
}
void dump(){
cout << "(" << x_ << ", " << y_ << ")" << endl;
}
};
int main(){
Point p(3, 1);
Point p1(10, 5);
p.add(p1);
p.dump();
p.sub(p1);
p.dump();
return 0;
}
And for the life of me I can not figure out why do the methods void add(Point P)
and void sub( Point p )
work.
Shouldn't I get an error like "cannot access private properties of class Point"
or something when I try to use add
or sub
?
Program compiled with gcc
version 4.6.3
(Ubuntu/Linaro 4.6.3-1ubuntu5)
.
When run it outputs:
(13, 6)
(3, 1)
Private keyword specifies that those members are accessible only from member functions and friends of the class. Private variables are accessable by the same type of objects even from other instances of the class.
This is not about security what lot of people think. This is about hiding internal structure of the class from other codes. It is required that a class won't mess up other instances by accident, thus no point to hiding variables from other instances. (Actually that would be a bit trickier to implement, and no or little reason to do so.)
private
members cannot be accessed from outside of a class except for friend
s, but can be from anywhere inside of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With