dimanche 26 mai 2019

c++11 modifying class private variable using reference variable

I was playing with reference variable. And I learned that I am able to directly modify class private variable from outside of class using its reference. Here's the code:

#include <iostream>
using namespace std;
#define print(x) cout<<x<<endl;

class prison
{
private:
    int victim;

public:
    prison(int ele)
    {
        victim = ele;                       
    }

    int & lophol()
    {
        return victim;    
    }

    void info()
    {
        print(victim)
    }
};

int main()
{
    prison sam{0};
    int &culprit = sam.lophol();
    culprit++;
    culprit++;
    sam.info();
}
Output:
$$ g++ -std=c++11 exp.cpp && ./a.out 
2

I can access private variable via reference. Is this behavior OK?

Aucun commentaire:

Enregistrer un commentaire