Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private functions of a class accessible?

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)
like image 877
Starburst Avatar asked Dec 03 '22 01:12

Starburst


2 Answers

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

like image 189
Matzi Avatar answered Dec 25 '22 22:12

Matzi


private members cannot be accessed from outside of a class except for friends, but can be from anywhere inside of the class.

like image 31
vinnydiehl Avatar answered Dec 25 '22 23:12

vinnydiehl