C++ operator overloading and private members

  • C/C++
  • Thread starter sir_manning
  • Start date
  • #1
sir_manning
66
0
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

  • #2
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,967
19
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.
 
  • #3
sir_manning
66
0
Aha... Thanks
 

Suggested for: C++ operator overloading and private members

  • Last Post
2
Replies
53
Views
2K
  • Last Post
Replies
18
Views
1K
Replies
23
Views
1K
  • Last Post
Replies
22
Views
811
  • Last Post
Replies
5
Views
1K
  • Last Post
Replies
5
Views
672
Replies
1
Views
546
Replies
4
Views
1K
  • Last Post
Replies
5
Views
5K
  • Last Post
3
Replies
89
Views
3K
Top