Pointer question: invalid conversion from int to int*

Why canĀ“t I access the pointer in MyClass that points at the variable v? How do I access it through a pointer?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyClass 
{
   private: 
      int v;
   public: 
      int *val;
      MyClass(){v = 5; val=&v;}
};

void function1(MyClass c) 
{
   c.val = 10;
}

int main()
{
   MyClass c;
   c.val = 5;
   function1(c);
}

I get "invalid conversion from 'int' to 'int*'.
Last edited on
You need to dereference the pointer:
*c.val = 10;

Pointer 101:
1) A pointer holds a memory address.
2) You need to dereference a pointer to store something in it.
3) You use the dereference operator * to do that.
4) The * has a different meaning when you declare the pointer variable (even in the parameter list of a function).
closed account (zb0S216C)
You need to dereference val when assigning it a value. For example: *c.val = 5;

Wazzak
Last edited on
Thanks!

Maybe a code pattern question: when is it preferable to use pointers to objects withing a class/struct (as the example above) rather than using a pointer to the class/struct itself to modify the members in the class/struct (as the example below)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyClass 
{
   public: 
      int val;
      MyClass(){val = 5; }
};

void function1(MyClass *c) 
{
   c->val = 10;
}

int main()
{
   MyClass *c = new MyClass;
   c->val = 5;
   function1(c);
}
Last edited on
Or can you allways use both methods?
1
2
3
4
void function1(MyClass *c) 
{
   c->val = 10;
}


Variable c can be NULL so do a check before referencing val.

e.g

if (c) c->val = 10;
Neither is more "preferable" than the other. It depends on the situation.
Also in your second example I think you should add:
1
2
delete c;
c = NULL;

Topic archived. No new replies allowed.