Below is the code
The Code:
#include
using namespace std;
class Rational {
int num; // numerator
int den; // den
Why C++ allow the parameter to access private data outside of the class ? Is it some kind of a special case?
The rule with access specifiers is:
"Access specifiers apply to per class and not per object"
So, You can always access private
members of a class object in member function of that class.
A copy constructor/copy assignment operator are commonly used examples of the rule though we do not notice it that often.
Online Sample:
class Myclass
{
int i;
public:
Myclass(){}
Myclass(Myclass const &obj3)
{
//Note i is private member but still accessible
this->i = obj3.i;
}
};
int main()
{
Myclass obj;
Myclass obj2(obj);
}
Good Read:
What are access specifiers? Should I inherit with private, protected or public?