29

I got the code from here.

class Timer {
 public:
  Timer();
};

class TimeKeeper {
 public:
  TimeKeeper(const Timer& t);

  int get_time()
  {
      return 1;
  }
};

int main() {
  TimeKeeper time_keeper(Timer());
  return time_keeper.get_time();
}

From the looks of it, it should get compile error due to the line:

TimeKeeper time_keeper(Timer());

But it only happens if return time_keeper.get_time(); is present.

Why would this line even matter, the compiler would spot ambiguity on time_keeper(Timer() ) construction.

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Shamim Hafiz - MSFT
  • 20,466
  • 38
  • 110
  • 169
  • possible duplicate of [Why is there no call to the constructor?](http://stackoverflow.com/questions/3810570/why-is-there-no-call-to-the-constructor) – mmmmmm Mar 08 '13 at 18:55
  • Does this answer your question? [Default constructor with empty brackets](https://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets) – Ken Y-N Oct 28 '20 at 08:13

1 Answers1

29

This is due to the fact that TimeKeeper time_keeper(Timer()); is interpreted as a function declaration and not as a variable definition. This, by itself, is not an error, but when you try to access the get_time() member of time_keeper (which is a function, not a TimeKeeper instance), your compiler fails.

This is how your compiler view the code:

int main() {
  // time_keeper gets interpreted as a function declaration with a function argument.
  // This is definitely *not* what we expect, but from the compiler POV it's okay.
  TimeKeeper time_keeper(Timer (*unnamed_fn_arg)());

  // Compiler complains: time_keeper is function, how on earth do you expect me to call
  // one of its members? It doesn't have member functions!
  return time_keeper.get_time();
}
Boaz Yaniv
  • 6,136
  • 20
  • 29
  • 3
    While I know the standard says in §13.1/3 that the Timer function type is adjusted to become a pointer to function type in this situation, but why would anyone want it to be adjusted to begin with? It seemed to me that §13.1/3 created the whole 'Most vexing parse' problem? – Zach Saw Feb 06 '14 at 02:35