Using pointer, I am able to modify the private value of the class in the code be
ID: 654939 • Letter: U
Question
Using pointer, I am able to modify the private value of the class in the code below.
Does it violate the C++ concept that private member can only be modified by member or friend functions?
#include<iostream>
using namespace std;
class demo
{
private: int info;
public:
demo()
{
info=10;
}
void print_info()
{
cout<<info;
}
};
int main()
{
demo ob;
int* ptr=(int*)&ob;
*ptr=20;
ob.print_info();
return 0;
}
Explanation / Answer
The C++ mechanism of public, protected and private members is meant to protect you from accidents, not from malicious intent.
Re-interpreting a pointer as if it points at something else (like you do with int* ptr=(int*)&ob) counts as 'malicious intent' and usually means that you are stepping beyond the C++ language. What happens is entirely up to the compiler and it does not have to be consistent in what it does.
Note that there are other ways to expose private data, for example:
class demo
{
private: int info;
public:
demo()
{
info=10;
}
int* expose_info()
{
return &info;
}
};
This is entirely legal in C++ (although usually a bad idea). The public/protected/private mechanism works only on names (so the name info is inaccessible for outsiders), but if you can get your hands on a pointer/reference to a private member, you have full access to that member.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.