1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ operator overloading and private members

  1. Apr 20, 2008 #1
    Good evening

    I'm in the midst of reviewing for my exam, I've come across a piece of code I don't understand. It is as follows:

    //////////////////////////
    #include <iostream>
    using namespace std;

    class number{

    private:
    int value;

    public:
    number(int v){value = v;}

    void operator + (const number & num){
    value = value + num.value; //<-what is going on here?
    }

    void print(){cout<<"\n"<<value<<"\n";}

    };

    int main(void){
    number five(5);
    number six(6);

    five+six;
    five.print();

    return 0;
    }

    ////////////////////////

    This code compiles and gives an output of 11. However, it seems to me that there is a privacy violation on the line indicated. How is it that the operator function can access a private member ("value") of another number class ("num")?

    Thanks.
     
  2. jcsd
  3. Apr 20, 2008 #2

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    That's not accurate: it is accessing a private member ("value") of a different instance ("num") of the same class ("number"). Since operator+ is a member of number, it has access to all of the private members of any instance of the number class.
     
  4. Apr 20, 2008 #3
    Aha... Thanks
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C++ operator overloading and private members
  1. C++ operator classes (Replies: 9)

  2. Ternary operator in C (Replies: 13)

Loading...