pointer to class instance problem

1
2
3
4
5
6
7
8
class x{int y;};

void test()
{
	x  q;
	x* xp;
	xp->q;
}


gives build error "line 7 : class x has no member q"
q is supposed to be an instance of the class x. Why should the class definition have to declare instances of itself alongside its own private variables?
Why is the builder ok with q as an instance of x when it is declared? But then decides it doesn't like q only when the pointer to x, xp, is pointed at q?
doesn't make sense. halp please.
Last edited on
xp is a pointer. Set its value to some address. What address? The address of q. How do we get the address of q? With &.

xp = &q;
The "->" operator does not assign what a pointer is pointing to. It takes what the pointer is pointing to and accesses a member out of it. You assign a pointer (point it at something) with the assignment operator "=". So, in your example, what you could do is:

1
2
3
4
5
6
7
8
9
class x {public: int y;}

void test()
{
    x q;
    x* xp;
    xp = &q;    // assign the address of q (& operator) to the pointer xp
    xp->y = 8;  // Assign the "y" value of the object pointed to by xp
}
Last edited on
woah, i had a major misunderstanding about the -> operator, and didn't know about &. last did c++ 19 year ago. That means I've had a wrong idea for 19 year.
fixed
thanks
Actually, I'm sure you had a firm understanding of -> and & 19 years ago. These operators have not changed since the beginning of C++, and they are pretty fundamental to the language.

So, your "wrong idea" evolved as your C++ memory got rusty. I'm sure that if I went back to some of my old Applesoft (BASIC) programs, there is syntax that I wouldn't remember after a few decades of non-use.

I hope you are enjoying your return to C++ after 2 decades. There is a lot to refresh, and a lot of new stuff to learn, too.
Registered users can post here. Sign in or register to post.