Short example of problem I have:

class A{
public:
    int x[10];
};

int main(){
    int A::*pointer = &A::x;
    
    A a;
    a.*pointer = 3;
    return 0;
}

I got an error: cannot convert from 'int (A::* )[10]' to 'int A::* ' in second line of 'main()'

I tried to remove '&' from this line because x is an array so the name of array (without square brackets) like A::x should return it's adress (in this case shift in A class), but now I got an error like this:

illegal reference to non-static member 'A::x'

Why compiler thinks I want to convert something? I just want to create a pointer to int array x[10], member of A class.
Could you help?

You're not doing it correctly -- you might want to try something like:

A a;
int *pointer;
pointer=a.x;

I haven't actually tried this code out, so it may not compile.

OK, but it is not what I'm trying to do.
I do not need a pointer to an member of object 'a' of type 'A'

I need a pointer to class member which can be created even before the object of such class is created and then used with this object, like this:

int A::*pointer = A::x;   //main problem: how to get adress (shift in class A) of member x
                                             //A::x doesn't return adress (shift) that I need
A a;
a.*pointer = 5

A b;
b.*pointer = 33;
etc.

But it doesnt work with this syntax, any other idea?

>>a.*pointer
that is incorrect syntax -- remove the star and add class member named pointer.

class A{
public:
    int x[10];
    int* pointer;
};

A a;
a.pointer = &a.x[0];

not just that, but you DO get an object instance when you do "A a;".
It's just created in a different memory space as compared to "A a = new A();".

>I feel I was not understood again, propably my fault.
Don't worry about it. Pointers to members aren't exactly a commonly used feature. The problem in your initial code is a type mismatch. x is an array, but to get a pointer to it, you need a pointer to an array member and you were only using a pointer to an int member:

class A{
public:
  int x[10];
};

int main(){
  int (A::*pointer)[10] = &A::x;

  A a;
  (a.*pointer)[0] = 3;
  return 0;
}

Unfortunately, this isn't a case where you can rely on the implicit conversion of an array name to a pointer to the first element of the array. To do that you would need to add another level of abstraction:

class A{
public:
  int x[10];
};

int main(){
  int (A::*pointer)[10] = &A::x;
  int *p;
  A a;

  p = a.*pointer;
  *p = 3;

  return 0;
}

Thank you very much for understanding me! Bye.

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.