Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use pointer to member inside a class object (right syntax)?

In this example i’m trying to return x, y or z from get_by_ptr function, but can’t unedrastand rigth(legal) syntax to do it. I understand that this pointer holds base address of object and pointer to member holds "address shift" and I can calculate address. But is there legal syntax way?

class foo {
public:
    size_t x{ 33 };
    size_t y{ 77 };
    size_t z{ 99 };
    size_t get_by_ptr(size_t foo::*ptr) {
        //how to return x, y or z using ptr
    }
};

int main() {
    foo bar;
    size_t foo::*ptr{ &foo::y };
    size_t z{ bar.get_by_ptr(ptr) };
}

Thank You.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You likely want to write:

size_t get_by_ptr(size_t foo::*ptr) {
    return this->*ptr;
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading