Search code examples
c++pointersclasspointer-arithmetic

Doing pointer math in a c++ class: Is it "legit"?


Ah-hoi, hoi,

I'm wondering if it's ok to do something like the following:

class SomeClass
{
   int bar;
};

SomeClass* foo = new SomeClass();
int offset = &(foo->bar) - foo;

SomeClass* another = new SomeClass();
*(another+offset) = 3; // try to set bar to 3

Just Curious, Dan O


Solution

  • I suppose tecnically it might work out.

    However, there are several problems. bar is private. You are mixing pointers of different types (pointer arithmetic relies on the pointer type: int* + 1 and char* + 1 have different results because int and char have a different size).

    Have you also considered pointers to members:

    #include <cassert>
    
    struct SomeClass
    {
       int bar;
    };
    
    int main() {
        int SomeClass::*mem_ptr = &SomeClass::bar;
        SomeClass foo;
        foo.*mem_ptr = 3;
        assert(foo.bar == 3);
    }