pointing to classes? newbie in need

C

Chris

I want to be able to point to a class, so I can change members of that
class with the pointer.
Here is the code:
###
class stuff {
public:
int a;
char b; };

int main() {
stuff junk;
junk.a=23; junk.b='c';
stuff * things = & junk;
*things.a = 1;
return 0; }
###
This is not compiling. Is there something I'm missing, or not
understanding?
Thanks for any help!
-Chris
 
D

Daniel T.

"Chris said:
I want to be able to point to a class, so I can change members of that
class with the pointer.
Here is the code:
###
class stuff {
public:
int a;
char b; };

int main() {
stuff junk;
junk.a=23; junk.b='c';
stuff * things = & junk;
*things.a = 1;
return 0; }
###
This is not compiling. Is there something I'm missing, or not
understanding?
Thanks for any help!
-Chris

You don't want to point to a class, you want to point to an object of
the class:

int main() {
stuff junk;
stuff* thing = &junk;
thing->a = 1;
(*thing).b = 'A';
}
 
I

Ian Collins

Chris said:
I want to be able to point to a class, so I can change members of that
class with the pointer.
Here is the code:
###
class stuff {
public:
int a;
char b; };

int main() {
stuff junk;
junk.a=23; junk.b='c';
stuff * things = & junk;
*things.a = 1;

Pointers are dereference with ->, not . this should be things->a = 1; or
(*things).a = 1;

return 0; }
###
This is not compiling. Is there something I'm missing, or not
understanding?
Thanks for any help!
-Chris
Also avoid more than one statement per line, readers don't expect it and
it makes code hard to read and debug.
 
J

John Carson

Chris said:
I want to be able to point to a class, so I can change members of that
class with the pointer.
Here is the code:
###
class stuff {
public:
int a;
char b; };

int main() {
stuff junk;
junk.a=23; junk.b='c';
stuff * things = & junk;
*things.a = 1;
return 0; }
###
This is not compiling. Is there something I'm missing, or not
understanding?
Thanks for any help!
-Chris

Just to make explicit what others have alluded to, *things.a = 1 doesn't
work because of the precedence with which different operators are applied.
You want to first dereference things and then call the dot operator. What
actually happens is that the dot operator is called first before the
dereferencing operator. Thus you are calling the dot operator on a pointer,
which is illegal.

You can work around this in two ways:

1. use (*things).a = 1;
2. use things->a = 1;

The pointer-dereferencing-and-member-selection operator -> used in 2. was
invented for the sole purpose of allowing you to avoid the syntax in 1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,110
Latest member
OdetteGabb
Top