Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(->) arrow operator and (.) dot operator , class pointer

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?

like image 980
lukai Avatar asked Jul 18 '13 06:07

lukai


People also ask

What is the difference between DOT and arrow operator?

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.

What is the difference between -> and C++?

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).

What is A -> B in C++?

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.

What does the dot operator do in C++?

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.


1 Answers

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

like image 114
Opsenas Avatar answered Oct 20 '22 00:10

Opsenas