Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is the difference between "." operator and "->" operator, in c++?

#include<iostream>

using namespace std;
class Science {
  int marks;
  public:
    void setMarks(int marks) {
      this -> marks = marks;
    }
  int getMarks() {
    return marks;
  }
};
void change(int * b) {
  * b = 20; //this works fine 
}
int main() {
  int x = 10;
  change( & x);
  cout << x << endl;
  Science z;
  Science * y = & z;
  z.setMarks(70);
  cout << z.getMarks() << endl;
  y -> setMarks(60); //this does not give error
  cout << z.getMarks() << endl;
  * y.setMarks(40); //why writing like this gives error
  cout << z.getMarks() << endl;
  return 0;
}

this code is written just to explain my question
I am also a bit confused in pointers,
as in the change function when I write *b=20 it is working as if writing x=20
so why writing *y.setMarks(40) not same as writing z.setMarks(40)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The . operator works on objects directly.

The -> operator accesses the object using a pointer; i.e. it dereferences the pointer first, and then uses the . operator.

for example, a -> b() is the same as (*a).b().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading