1

I don't understand this code which should provide a different behavior in C and C++ ( Can code that is valid in both C and C++ produce different behavior when compiled in each language?)

#include <stdio.h>

struct f { };

int main() {
    f();
}

int f() {
    return printf("hello");
}

Why can I call f() in C++? Is it the default constructor (which I don't see by the way, is there another one "implicit"?)? In C++ that is not calling the f() function..

Community
  • 1
  • 1
Johnny Pauling
  • 12,701
  • 18
  • 65
  • 108
  • 5
    That's _value-initializing_ an instance of `f` then immediately destroying it, and yes, there is an implicitly-generated default constructor for `f`. – ildjarn Oct 16 '12 at 22:41

2 Answers2

2

Every class has an implicit default constructor, unless you define other constructor. This definition of the class f:

struct f { };

Is equivalent to:

struct f { 
    f() = default;
    // same for copy constructors, move constructors, destructor, etc
};

So yes, inside main, you're value initializing(or default initializing, it's the same here), an object of type f.

As of why it's not calling the function f, well, inside main there is no declaration nor definition of the function f available. The only visible symbol named f is the struct defined above.

mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • Is it allowed to define a function with the same name as a struct? – Joseph Mansfield Oct 16 '12 at 22:46
  • 1
    The expression `f()` is **not** a call to the constructor. It is *value-initialization* of a temporary object. The difference is that for a POD type `f()` guarantees that all fields are *zero-initialized*, but the implicitly-defined default constructor would leave the fields uninitialized. – David Rodríguez - dribeas Oct 16 '12 at 23:20
  • I'm thinking maybe the "is equivalent to" should also have copy constructor, move assignment, destructor, etc? – Mooing Duck Oct 16 '12 at 23:20
  • @DavidRodríguez-dribeas at no point did I state that `f()` is a call to a constructor. Or am I missing something in my answer? – mfontanini Oct 16 '12 at 23:34
  • @MooingDuck yes, well, my answer was regarding only default constructors, but you're right. – mfontanini Oct 16 '12 at 23:35
2

In C++, the expression T() where T is a type is the creation of a temporary that is value-initialized. Note that this is different from a call to the constructor in general (in particular it is different for POD types).

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489