What's the difference between . and ->

There are two operators . and -> in c++,I know when you want to get a variable or function of an object of a class,you should use .
But when I want to get a functions and variables from a pointer ,I see they both can use and seem same.So what's the difference between them?
Last edited on
a->b is the same as doing (*a).b.

So, you use -> when you have a pointer to an object. You use . when you have the object itself.

1
2
3
4
5
6
7
8
9
10
11
12
struct MyStruct {
  int val;
}

MyStruct a;
a.val = 5;
std::cout << a.val << std::endl;  // Displays 5

MyStruct* b = &a;  // b is a pointer, pointing to a.
b->val = 10;
std::cout << b->val  << std::endl;  // Displays 10
std::cout << a.val << std::endl;  // Also displays 10 
Last edited on
Hoping I can get reply quickly,thanks.
I've read this answer
a->b is the same as doing (*a).b.

So, you use -> when you have a pointer to an object. You use . when you have the object itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	

struct MyStruct {
  int val;
}

MyStruct a;
a.val = 5;
std::cout << a.val << std::endl;  // Displays 5

MyStruct* b = &a;  // b is a pointer, pointing to a.
b->val = 10;
std::cout << b->val  << std::endl;  // Displays 10
std::cout << a.val << std::endl;  // Also displays 10  



But what does b.val mean?
But what does b.val mean?

Nothing. It's illegal syntax, assuming b is a raw pointer.

Or are you talking about smart pointers?
Topic archived. No new replies allowed.