0

I am learning C++ in a advanced programming class from my work since I have only worked in Web and .NET languages so far. In a midway test the instructor has marked all of my uses of (*a).b as wrong and deducted points for it, which could negatively affect my final score and I need a near perfect score to transision in work from web stack to application stack, so could some of you help me resolve this dispute?

Voltex
  • 56
  • 1
  • 7
  • Please provide an example and be as specific as possible. – schaiba Dec 09 '19 at 09:19
  • 2
    They are equivalent; The "->" is just syntactic sugar – Tom Dec 09 '19 at 09:22
  • 1
    They are equivalent, but the arrow is less of an ugly kludge when you have it as part of a more complicated expression. Which is probably why your instructor doesn't want you to do `(*a).b`. In the end, code quality doesn't only include that the code does what it is supposed to do, but also that it is maintainable and can be easily understood. – Blaze Dec 09 '19 at 09:25
  • Obviously, (*a).b is correct in (almost, see Quentin's answer) all cases, so you could argue that the point deduction wasn't justified. In reality, I prefer a->b because it's more concise. – Ser Jothan Chanes Dec 09 '19 at 09:27

1 Answers1

7

If a is a pointer, there's no difference in functionality at all, and in fact one is expressed in terms of the other [expr.ref§2]:

The expression E1->E2 is converted to the equivalent form (*(E1)).E2; the remainder of [expr.ref] will address only the first option (dot).

If a is an instance of a class with overloaded operators * and ->, there could be a difference. But such a discrepancy would be surprising, and I'd consider the class to have a bug because of this.

In the end, it's all about convention and readability then. The -> operator exists as a shorthand for the */. pair, as it is shorter and has better precedence rules (no need for parentheses). Thus, one would indeed use it rather than */..

Quentin
  • 62,093
  • 7
  • 131
  • 191