private section of Qt classes is not safe

I have define a QByteArray class as arr instance in Qt. normally, private members of QByteArray(and another classes) are not accessible, else use of friend members in class.

Attention bellow code :

void Widget::onBtnRun()
{
    QByteArray arr;
    arr = "this is a test";
    arr.d->size = 5;                  // stop with compile error-> QByteArray::d is private
    QMessageBox::information(this, "", arr);
}

the d member of QByteArray is private and cannot access to that!

but i have edited QByteArray header file, so adding bellow line in it's class section, then save that again.

public :
     friend Class Widget;

And now i can access to the private members of QByteArray class in Widget class, without any problem :

void Widget::onBtnRun()
{
    QByteArray arr;
    arr = "ABCDEFGHIJKLMNOPQRSTUV";
    arr.d->size = 5;
    QMessageBox::information(this, "", arr);
}

MessageBox output now is "ABCDE".

Is this a lack for classes? perhaps this cause appear very problem in future. how can save private members from thease problems?

Thanks in advance!

Upvotes: 0

Views: 242

Answers (2)

The class member access modifiers in C++ have nothing to do with security. They are there to express design intent that is enforced by the compiler. They are not used to "hide"/obfuscate code or prevent access by third parties.

Quoting this excellent answer:

In general, access controls names or symbols, not the underlying entities. There are, and always have been, numerous ways of accessing private members; what you cannot do is use the name of such a member.

Why do you consider this a problem? What are you trying to "protect" yourself/your code from?

Upvotes: 3

Stivius
Stivius

Reputation: 72

I think there is no way to do this. If someone can access your header file, he could do potentially anything with your class. If you are developing a simple executable application, you should not worry about this because other users cannot access your source files. In case of library you can make its dynamic and provide only .so/.dll file.

If you edit someone's header file, you will do it on your own risk.

Upvotes: 4

Related Questions