0

Say I have this code

std::string s = "hello";
std::string* p = &s;
int l = p.length();

Visual Studio and CLion know dot operator is incorrect. Actually when I press key ., both IDE commit the keystroke as ->.

Since C++ is typed, it knows p is a pointer, why doesn't it combine . and -> into one?

Can the syntax be to always use ., if p is pointer, dereference it first, otherwise directly get its member?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Gqqnbig
  • 5,845
  • 10
  • 45
  • 86

1 Answers1

4

Classes can overload the arrow operator, so there can be objects for which both . and -> are valid. Smart pointers (e.g. std::unique_ptr or std::shared_ptr) and iterators are common examples.

std::unique_ptr<Foo> f;
f.reset(new Foo(42));
f->bar();

Could you design a statically typed language without this distinction? Of course. But C++ has evolved this way, and that's not something you can change today without breaking tons of code.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • 3
    If you read the duplicate, it becomes somewhat evident that C++ got the arrow operator purely by luck - we might never have it! Which would mean that overloading it would not be possible either (luckily it would not be introduced specifically for C++), and we wouldn't have smart pointers! – SergeyA Apr 23 '19 at 19:45
  • @SergeyA they are actually super interesting bits of history (from a time when C was way more similar to a glorified macro assembler) that I didn't know, thank you! – Matteo Italia Apr 23 '19 at 20:10