C++ operator overloading and private members

  • C/++/#
  • Thread starter sir_manning
  • Start date

Main Question or Discussion Point

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.
 

Answers and Replies

Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,843
17
How is it that the operator function can access a private member ("value") of another number class ("num")?
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.
 
Aha... Thanks
 

Related Threads for: C++ operator overloading and private members

  • Last Post
Replies
5
Views
2K
Replies
4
Views
2K
Replies
1
Views
4K
Replies
4
Views
504
Replies
3
Views
2K
  • Last Post
Replies
6
Views
2K
Replies
1
Views
996
Top