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{

    int value;

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


    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")?

  2. jcsd
  3. Apr 20, 2008 #2


    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
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook