assignment problem

Hi all, i have a class and i try to initialize the variable of a class through constructor in this way:

1
2
3
4
5
6
class one
{
 one(int k):*a(k){}

 int *a;
};


but it doesn't work instead of this which works fine

1
2
3
4
5
6
class one
{
 one(int k){*a=k;}

 int *a;
};


Why is that? Thanks
Last edited on
one(int k){*a=k;} That doesn't work. You are dereferencing garbage.
one(int k):*a(k){} That isn't the constructor of the pointer.
try:

one(int k) : a(new int(k)) {}
Cool thanks quirkyusername, indeed it works!

ne555 why Do you say one(int k){*a=k;} doesn't work?It pases the value of an integer variable to the containing value of a pointer.Am i wrong? I don't know if it is safe(although it looks like) but it works to me.
Last edited on
It pases the value of an integer variable to the containing value of a pointer.Am i wrong?


The problem is 'a' doesn't point to anything. You can't assign a value to what the pointer points to unless it actually points to a variable. Otherwise you're just writing the value to random memory -- causing heap corruption and possibly a program crash.
is this acceptable ?

1
2
3
4
5
6
class one
{
 one(int k){a=new int; *a=k;}

 int *a;
};
yes but what was wrong with the above example?
ok, i got your point .
Topic archived. No new replies allowed.