Re: Why do constructors have same name as the class ?
This is kind of an old thread; but just to clarify in case somebody
finds this some day:
On Feb 26, 8:04 pm, In the Middle of the Pack <a...@nospamcentral.com>
wrote:
Some people maintain that a constructor *does* return something -- it
returns a new instance. Since an new instance is the *only* thing a
constructor is allowed to return, by allowing the programmer to specify a
return type or "return <something>;" ("return;" is O.K.), this would allow
the programmer to mess it up. So, these syntactic elements are not
available in the constructor's syntax -- the opportunity to make one of
these errors is taken away.
I see where you are going with your explanation, but it is misleading.
People that maintain that a constructor returns something are
incorrect. That is not the case. A constructor simply initializes a
block of allocated memory. When you call "new", first some memory is
allocated (you can even allocate the memory yourself, Google for
"placement new"), then the constructor is called to perform any
initialization of data in that block. It doesn't return anything. When
you do "Object *a = new Object();", it's actually the new operator
that is returning something (a pointer to a block of memory
initialized by your constructor), not your Object() constructor.
In C, you may have done something like this (you may have even seen
code like this before; it can get hard to look at):
typedef struct {
int i;
} A;
typedef struct {
int k;
A a1;
A a2;
} B;
/* initialize members of an A */
void Construct_A (A *a) {
a->i = 0;
}
/* initialize members of a B */
void Construct_B (B *b) {
b->k = 0;
Construct_A(&b->a1);
Construct_A(&b->a2);
}
/* allocate and initialize a new B */
B * New_B (void) {
B *b = (B *)malloc(sizeof(B));
Construct_B(b);
return b;
}
/* destroy a B */
void Delete_B (B *b) {
free(b);
}
But in C++, constructors and destructors exist to make things like
that much more convenient:
class A {
public:
A (void) : i(0) { }
int i;
};
class B {
public:
B (void) : k(0) { }
int k;
A a1;
A a2;
};
That small bit of C++ does basically the same thing as the above C
code. But constructors basically just initialize memory, that's all.
They don't return anything. It's the "new" operator that returns
pointers. So the reason they don't let you "return" things from
constructors isn't because a "programmer might mess it up", it's
because it has no meaning for a constructor.
Jason