No, a constructor of
object is very different from a function called
object and returning
object. A constructor has no name, but that is largely a technicality. The more important differences are that a constructor has no return type and that it cannot be called directly.
A constructor doesn't return anything because it is given a block of memory and operates on that memory in-place. It might help if you forget the name "constructor" for a moment and think of it as initialiser instead. The purpose of the constructor is not to construct an object "out of thin air." Its purpose is to initialise an object at the precise place in memory where it needs to be.
If a constructor was to return an object, that returned object (the return value) would have to live somewhere (probably on the stack), and there, it would need to be initialised somehow — we're running into a loop here.
This goes hand in hand with the fact that a constructor can never be called directly. If you have a class
object and use an expression
object() somewhere, it does not have the semantics of "call the constructor of
object." It has the semantics of "create a temporary object of type
object." The compiler translates this into allocating some place for the temporary to live in (probably/commonly on the stack), and calling the constructor to construct (= initialise) an object in that place.
The same principle applies when using
new object(). This is a new-expression, which does two things:
- Call an allocation function
operator new (which returns a
void*) to allocate raw memory for the object.
- Issue a constructor call on this raw memory to construct (= initialise) an object in that piece of raw memory.
Thinking of a constructor of
object as a function like this:
static object object();
is wrong. If anything, the way a constructor works is closer to this:
static void object(object &place_to_work_in);
With the exception that you can never call it directly. It is always only called when specified by a different language construct. Even placement new (also known as the "call a constructor here" trick),
new (&place_for_object) object(), doesn't call the constructor directly. It translates into a call to the placement-new form of
operator new which returns its argument, followed by a call to the constructor (just like any other new-expression).