#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 :
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().