2

I was reading about structs and struct padding and I wrote this code. It edits a private member of a struct using its address offset from a. Does this mean you can take a class someone made and extract/change private varriables and functions?

#include <iostream>
typedef struct x {
    int a; 
private:
    int b;
public:
//Init
    x(int a, int b) : a(a) , b(b){}

    void print(){
        //Print values
        std::cout << a << " " << b << std::endl;
    }
} x;

int main()
{
    struct x s(10,20) ;
    int *p = (int *)(((char*)&s)+4); //4 Byte offset from a (a is at base)
    s.print();
    (*p) +=1;
    s.print();

    //Stops terminal closing
    int junk;
    std::cin >> junk;
    return 1;
}
uchar
  • 2,552
  • 4
  • 29
  • 50
cbkrunch
  • 45
  • 8
  • 5
    No, it is just *undefined behaviour*. – juanchopanza Jun 02 '14 at 15:35
  • 2
    *private* is about protecting against Murphy, not Machiavelli. – wonce Jun 02 '14 at 15:42
  • 1
    Related: [Is C++ private really private?](http://stackoverflow.com/questions/2273091/c-is-private-really-private) – legends2k Jun 02 '14 at 15:50
  • I have used this to prove that a bug lay in someone elses code (by "fixing" their private member data). The tidier way to do it is to create your own header for the class with a new name and everything public, then reinterpret cast from the one to the other. Just, please, for the love of sanity, do this only for temporary hacky testy purposes. It is good, however, to know this, because otherwise people will rely on private to do things it doesn't. – Andy Newman Jun 02 '14 at 15:52
  • [access to private members: safer nastiness](http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html) – Ryan Haining Jun 03 '14 at 01:31

2 Answers2

5

C++'s private is for giving abstract data types an encapsulation mechanism. It's not for preventing people from writing bad code if they really want to.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
1

Does this mean you can take a class someone made and extract/change private varriables and functions?

The C++ standard imposes no requirements on such matter. Specifically there are no requirements on the size of the objects inside a struct. The size of int is implementation defined.

It's probably a bad idea and most likely a design smell.

Shoe
  • 74,840
  • 36
  • 166
  • 272