In C++ we know that for a pointer of class we use (->
) arrow operator to access the members of that class like here:
#include <iostream>
using namespace std;
class myclass{
private:
int a,b;
public:
void setdata(int i,int j){
a=i;
b=j;
}
};
int main() {
myclass *p;
p = new myclass;
p->setdata(5,6);
return 0;
}
Then I create an array of myclass
.
p=new myclass[10];
when I go to access myclass
members through (->
) arrow operator, I get the following error:
base operand of '->' has non-pointer type 'myclass'
but while I access class members through (.
) operator, it works. These things make me confused. Why do I have to use the (.
) operator for an array of class?
The Dot(.) operator is used to normally access members of a structure or union. The Arrow(->) operator exists to access the members of the structure or the unions using pointers.
You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).
So for a.b, a will always be an actual object (or a reference to an object) of a class. a →b is essentially a shorthand notation for (*a). b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that points to.
operator in C/C++ The dot (.) operator is used for direct member selection via object name. In other words, it is used to access the child object.
you should read about difference between pointers and reference that might help you understand your problem.
In short, the difference is:
when you declare myclass *p
it's a pointer and you can access it's members with ->
, because p
points to memory location.
But as soon as you call p=new myclass[10];
p
starts to point to array and when you call p[n]
you get a reference, which members must be accessed using .
.
But if you use p->member = smth
that would be the same as if you called p[0].member = smth
, because number in []
is an offset from p
to where search for the next array member, for example (p + 5)->member = smth
would be same as p[5].member = smth
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With