Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not so obvious pointers

Tags:

c++

pointers

I have a class :

class X{
 public :
 void f ( int ) ;
 int a ;
} ;

And the task is "Inside the code provide declarations for :

  • pointer to int variable of class X
  • pointer to function void(int) defined inside class X
  • pointer to double variable of class X"

Ok so pointer to int a will be just int *x = &a, right ? If there is no double in X can I already create pointer to double inside this class ? And the biggest problem is the second task. How one declares pointer to function ?

like image 264
mike_hornbeck Avatar asked Feb 27 '26 16:02

mike_hornbeck


2 Answers

These are called pointers to members. They are not regular pointers, i.e. not addresses, but "sort-of" offsets into an instance of the class (it gets a bit tricky with virtual functions.) So:

  1. int X::*ptr_to_int_member;
  2. void (X::*ptr_to_member_func)( int );
  3. double X::*ptr_to_double_member;
like image 160
Nikolai Fetissov Avatar answered Mar 01 '26 18:03

Nikolai Fetissov


You need to declare them as pointer-to-members. Pointers to members are different than usual pointers in that they are the address of a member of a structure or class, not an absolute address like regular pointers.

For more information, read this.

like image 32
Ramon Zarazua B. Avatar answered Mar 01 '26 17:03

Ramon Zarazua B.