Why do constructors have same name as the class ?


Y

yeti

Hi,
I have few simple question.
1. Why does the constructor and destructor have same name as the class
it
belongs to ??

2. Why can't constructor and destructor return values ??

regards

Rohin
 
Ad

Advertisements

F

Fabian Lenzen

Hi,
I have few simple question.
1. Why does the constructor and destructor have same name as the class
it
belongs to ??

It’s regarded as a good method to make it a ctor. It is only a convention.
2. Why can't constructor and destructor return values ??

The ctor returns the object. It cannot return anything else. And the dtor: Where could you save the dtors return value? Normally, you don’t call the dtor, only of you’re overwriting operator delete()
 
M

Mike Wahler

yeti said:
Hi,
I have few simple question.
1. Why does the constructor and destructor have same name as the class
it
belongs to ??

Constructors don't have names. The syntax makes it
look like they do.
2. Why can't constructor and destructor return values ??

What values should they return, and how would you use them?

-Mike
 
J

James Kanze

I have few simple question.
1. Why does the constructor and destructor have same name as
the class it belongs to ??

Because Stroustrup designed it that way. I suspect that the
main motivation at the time was just to avoid introducing new
keywords.
2. Why can't constructor and destructor return values ??

How could they? You can't call a constructor directly, and you
don't normally call the destructor directly. So even if they
did have a return value, you'd have no way of accessing it.
 
T

Tim Slattery

Fabian Lenzen said:
It’s regarded as a good method to make it a ctor. It is only a convention.

No, it's because the language specification says that it does. That's
how you tell the compiler which method is the constructor.
 
Ad

Advertisements

A

Alf P. Steinbach

* James Kanze:
Because Stroustrup designed it that way. I suspect that the
main motivation at the time was just to avoid introducing new
keywords.

Also to support the idea of seamless type conversion, I guess. When it
looks like you're calling T(x), it makes a kind of sense to have the
invoked function named T. Except that it's really T::T, so the illusion
breaks down very very rapidly, and just incurs a host of problems...

How could they? You can't call a constructor directly, and you
don't normally call the destructor directly. So even if they
did have a return value, you'd have no way of accessing it.

Well. In early (pre-standard) C++ you could assign to 'this'. Not
'*this', but 'this'. :)

So one might say that what a constructor returned then, technically, was
the address of the constructed object. But that was under the hood.

What's interesting here is that the C++ constructor mechanism really
requires exceptions of some kind. Because objects need not be
dynamically allocated, so failure can't be signalled via 'this'. And
that this breaks down in environments that don't support exceptions.

And one sort-of-obvious alternative design for such environments could
be where you can declare storage for an object of a type T without the
ability to use that storage directly, but only through a typed pointer
returned by a constructor. And... Hey, C++ supports that already! <g>

At least, sort of. A little helper machinery would help much. Using
temporaries would be a problem, I think (interesting to think of
possible solutions for supporting that...).


Cheers,

- Alf
 
I

Ian Collins

yeti said:
Hi,
I have few simple question.
1. Why does the constructor and destructor have same name as the class
it
belongs to ??

2. Why can't constructor and destructor return values ??
Compatibility with built in types must be a part of both answers.
 
V

Victor Bazarov

Ian said:
Compatibility with built in types must be a part of both answers.

"Compatibility"? In what sense? Or, do you mean "consistency"?
I am not good at English, sorry...

V
 
A

Andre Kostur

Hi,
I have few simple question.
1. Why does the constructor and destructor have same name as the class
it
belongs to ??

Why not?
2. Why can't constructor and destructor return values ??

Return values to where? What's your use-case for having these return
values?
 
Ad

Advertisements

J

James Kanze

* James Kanze:
Also to support the idea of seamless type conversion, I guess. When it
looks like you're calling T(x), it makes a kind of sense to have the
invoked function named T. Except that it's really T::T, so the illusion
breaks down very very rapidly, and just incurs a host of problems...

Especially as T(x) doesn't necessarily call T::T---it might also
call TypeOfX::eek:perator T.

I think the real question is simply: if it's going to be defined
like a function, it needs some sort of name. And at the time
constructors were introduced (very, very early in the language),
there was still some sort of resistence to adding
keywords---arguably, a special keyword name, like "constructor"
or "destructor" would have been more appropriate.

But I don't think it really matters that much. The current
situatation doesn't cause any real problems either.
Well. In early (pre-standard) C++ you could assign to 'this'. Not
'*this', but 'this'. :)

Been there, done that. Assignment to this was only allowed in
the constructor, only before you accessed any members, and had
special semantics (basically, the equivalent of defining a
member operator new() today).
So one might say that what a constructor returned then,
technically, was the address of the constructed object. But
that was under the hood.

I suspect that there are still some implementations that do this
under the hood. The orginal CFront passed the address of a
object to be constructed to the constructor, or a null pointer
if the memory was to be allocated dynamically. The code
generated for the constructor tested for null, and called new,
And the constructor did return the pointer, which was what was
assigned in something like "p = new ...".

One might also say that an expression like 'T(x)' calls the
constructor, and returns an object. From a users point of view,
that's fairly close to the way a lot of people think of it.
What's interesting here is that the C++ constructor mechanism really
requires exceptions of some kind. Because objects need not be
dynamically allocated, so failure can't be signalled via 'this'. And
that this breaks down in environments that don't support exceptions.

It would need exceptions even if it returned the pointer,
because there would be no way of accessing it in the declaration
of a local variable. (But that's really subsumed in what you
said.) More generally, constructors guarantee the invariants of
an object---if a constructor can't do that, you need some sort
of mechanism which guarantees that the object doesn't exist.
Given local and static variables, it's hard to imagine what that
mechanism could be, if it wasn't exceptions.
And one sort-of-obvious alternative design for such environments could
be where you can declare storage for an object of a type T without the
ability to use that storage directly, but only through a typed pointer
returned by a constructor. And... Hey, C++ supports that already! <g>
At least, sort of. A little helper machinery would help much. Using
temporaries would be a problem, I think (interesting to think of
possible solutions for supporting that...).

One could imagine all sorts of things. However...

Is the current situation really broken? Does it need fixing?
(IMHO, the only really viable alternative would be to require
all objects to be allocated on the stack, a la Java. Which has
other disadvantages.)
 
R

Raymond

Andre said:
Return values to where? What's your use-case for having these return
values?

Instead of using exceptions, and also saving the user from calling
another function after the object has been constructed, to see whether
it was succesful in initializing itself.

class Example
{
public:
Example (bool & initialized)
{
initialized = false;
}
};

int main ()
{
bool e_initialized;
Example e (e_initialized);
if (e_initialized)
{
}
}
 
Y

yeti

Why can't we instead have an init() function in each class to serve as
constructor ? I just wanted to know why is name of constructor same as
that of the class. I'm not saying that it should not be this way..I'm
just asking why is it this way.
Return values to where? What's your use-case for having these return
values?
If constructors could return values they could possibly return error
codes if object construction failed.
 
I

Ian Collins

yeti said:
If constructors could return values they could possibly return error
codes if object construction failed.
How would you access the return value?
 
Ad

Advertisements

J

James Kanze

If constructors could return values they could possibly return error
codes if object construction failed.

A constructor establishes the class invariants. If it fails,
the class invariants can't be established. Which means that the
instance of the class shouldn't exist.

In sum, what we get with exceptions.
 
I

In the Middle of the Pack

yeti said:
Hi,
I have few simple question.
1. Why does the constructor and destructor have same name as the class
it
belongs to ??

2. Why can't constructor and destructor return values ??

regards

Rohin

Well, the destructor doesn't really have the same name as the constructor
and class does it? Isn't the ~ part of the name?

As some of the other replies have suggested, this naming convention seems to
help simplify the language by avoiding additional keywords.

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. Not sure if this view is legitimate or
pedagogy.

Now, a destructor is going to destroy an instance, so it can return neither
its object nor any part of its object. Just what else might you like it to
return?
 
J

jason.cipriani

This is kind of an old thread; but just to clarify in case somebody
finds this some day:

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
 
Ad

Advertisements

J

jason.cipriani

...
/* destroy a B */
void Delete_B (B *b) {
free(b);

}

But in C++,constructorsand destructors exist to make things like
that much more convenient:
...

I forgot to mention destructors. A destructor would fit in like this
in that C code:

void Delete_B (B *b) {
if (b != NULL) Destruct_B(b);
free(b);
}

Where "Destruct_B" would free any memory allocated by
"Construct_B" (like if some members of B were arrays or something that
Construct_B allocated), and would also call a hypothetical
"Destruct_A" on all those A's. In the C++ code, of course, the
destructor would just be "~A () { }" and "~B () { }" in the
appropriate places. Destructors didn't really fit in with the example
I gave though -- sorry, it was not the most comprehensive example.

Jaso
 

Top