Search code examples
c++ooppointersprivate

why c++ allows pointers if they can generate problems like accessing private members?


I have read about c++ pointers and their pitfalls, one of which is that one can access private data members of other class objects using pointer hacks as mentioned here and here. Surely pointers in c++ gives a lot of flexibility to the language but what's the use of it if it can hamper the core OOP features of the language like data hiding ? Is this really a trade-off between security & flexibility ?


Solution

  • C++ was originally built on the C language. It added features without removing any. C had pointers and therefore C++ has pointers. Compatibility with the C interface remains an essential feature of C++. Therefore pointers will never be not-allowed.

    Besides compatibility, pointers are very useful. Introducing object oriented programming to a system programming language being the initial reason for C++, it should be noted that indirection is essential for implementing runtime polymorphism. Sure, there is another method of indirection in C++ - references, but references are more limited and cannot be used to implement all algorithms that require the use of pointers.

    Pointers are also required to implement node based data structures such as trees or linked lists.

    c++ pointers and their pitfalls, one of which is that one can access private data members of other class objects using pointer hacks as mentioned here

    That trick isnt so much enabled by the pointer but by the use of reinterpret_cast. It would be much more sensible to question why that language feature is allowed.

    and here

    Both this and the previous are cases where the language does not allow breaking of encapsulation. The problem isn't the pointer. The problem is that C++ - like C - has undefined behaviour (UB) when certain rules are violated.

    You might be wondering, why does a language have UB. The answer is that if the rules were required to be checked at runtime to avoid UB, the program would necessarily be slower than it could be when we assume that the program didn't make a mistake. Since C and C++ are low level system programming languages, performance was chosen at the cost of protecting against bad programmers.