Search code examples
c++qtclassprivate-members

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!


Solution

  • 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?