C/C++ C++ operator overloading and private members

AI Thread Summary
The discussion revolves around a piece of C++ code that defines a class named "number" with a private integer member "value." The user is confused about how the overloaded operator+ function can access the private member "value" of another instance of the same class. It is clarified that since operator+ is a member function of the "number" class, it has access to the private members of any instance of that class, including the instance passed as a parameter. The code compiles successfully and outputs 11 when the operator+ function is invoked, demonstrating the functionality of operator overloading in C++.
sir_manning
Messages
64
Reaction score
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.
 
Technology news on Phys.org
sir_manning said:
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
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Back
Top