#include <iostream>
using namespace std;

class X{
      public:
             int p;
      };
      
int main(){
    int b;
    X obj;
    int X::*ptr = &X::p;
    obj.p = 100;
    cout<<obj.p<<endl;
    cout<<ptr<<endl;
    cout<<obj.*ptr<<endl;
    system("pause");
    return 0;
}

When i run this program, i get the output as:
100
1
100.

I understand why it shows 100...but what i do not understand is that why does cout<<ptr<,endl outputs 1. Isn't it should be pointing the address of variable p? Thanks a lot!!

Isn't it should be pointing the address of variable p?

You can't expect a pointer to member to be printable at all, actually. The term "address" is used to mean "reference to a location", which for practical reasons compilers have implemented as a physical or virtual memory address. However, that's not required at all even for regular pointers. Pointers to members are especially confusing because they're still an "address", but a simple pointer can't be used due to the potentially complex nature of the class structure.

Usually some form of thunk is used instead as an offset into the class.

Since it is a pointer, what you are doing is printing the address of the pointer, not the contents. Try "cout << *ptr << endl;" instead.

Since it is a pointer, what you are doing is printing the address of the pointer, not the contents.

Pointers are confusing for many people, so you should be especially precise with your phrasing. The address of a pointer is not the same as the address stored by a pointer. The contents of a pointer is the address stored.

The question was why is the address stored by a pointer to member not equivalent to the expected format of a memory address when printed. And the answer was a pointer to member does not store a memory address, it stores sufficient information to provide an offset into the target class when applied to an object of that class.

Try "cout << *ptr << endl;" instead.

Note that the discussion is about pointers to members, not regular pointers. They're most certainly not the same thing, hence the wildly different (and awkward, in my opinion) syntax.

Narue, I agree that the C++ pointer-to-member syntax is confusing and prone to incorrect usage. The last time I had to program such constructs I remember that I had to try a number of different approaches in order to get the desired results! Anyway, as always, your comments are to the point, and cogent. Thanks!

Thanks a lot Narue & rubberman!!. It helps.....

We lurk in order to help! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.