function pointer to constructor

M

Morten Lemvigh

Is it possible to pass a pointer to a constructor or a class definition
as argument to a function? Maybe in a way similar to passing function
pointers...?

The function should construct a number of objects using the given
constructor. The objects should all inherit from a base class.

It's not possible to pass actual objects, since it's not given on
beforehand, how many should be created.

Thanks,
Morten
 
J

jkherciueh

Morten said:
Is it possible to pass a pointer to a constructor or a class definition
as argument to a function? Maybe in a way similar to passing function
pointers...?

Not directly. The standard somewhat ominously says that constructors have no
names. As a consequence, I think, you cannot obtain a function pointer to a
constructor.

But you can write functions that construct objects. E.g.,

template < typename T >
T* create ( void ) {
return ( new T() );
}

template < typename T, typename Arg1 >
T* create ( Arg1 const & arg1 ) {
return ( new T ( arg1 ) );
}

...

Then you could pass &create<MyType,MyArg> as a function pointer. However,
the signature of that function would depend on the actual types used. Thus,
the receiving function might need to be a template

template < typename Creator >
void some_function ( Creator create ) {
}

In that case, you could go all the way and turn create into a full-fledged
functor:

template < typename T >
struct creator {
typedef T value_type;
typedef T* pointer;

pointer operator() ( void ) const {
return ( new T () );
}
};

The function should construct a number of objects using the given
constructor. The objects should all inherit from a base class.

It's not possible to pass actual objects, since it's not given on
beforehand, how many should be created.

Huh? So how would it be determined? Could you provide a little more
background?


Best

Kai-Uwe Bux
 
J

James Kanze

Not directly. The standard somewhat ominously says that
constructors have no names.

More to the point, there is no way in the standard of "calling a
constructor", period. All of the contexts where a constructor
is called also involve allocating memory for the object. If you
try to call the constructor through a pointer to a function, how
would the compiler know where (stack?, dynamically?) or how much
memory to allocate?

(I suppose one could claim that placement new just calls a
constructor. But from the language point of view, it's a new
expression, which calls an operator new() function to get the
necessary memory.)
 
J

jkherciueh

James said:
More to the point, there is no way in the standard of "calling a
constructor", period.

There is also no way of "calling a function" either. All that there is,
according to the standard, is that a function call expression is evaluated
and in the course of the execution of that evaluation, a function will be
called (but sometimes more happens: in the case of virtual functions, there
might even be some mechanism involved behind the scenes to decide which
one).

Similarly, there are expressions whose evaluation involves the call of
constructors (and usually much more). In fact, there are several.

Despite this, I take the linguistic license to say that I call a function.
Also, I don't see a reason not to take the same linguistic license with
constructor calls.

But, actually, this terminological issue is not "more to the point" of the
OP.
All of the contexts where a constructor
is called also involve allocating memory for the object. If you
try to call the constructor through a pointer to a function, how
would the compiler know where (stack?, dynamically?) or how much
memory to allocate?

This, on the other hand, is. However:
(I suppose one could claim that placement new just calls a
constructor. But from the language point of view, it's a new
expression, which calls an operator new() function to get the
necessary memory.)

Well, C++ just provides a very very roundabout way to call a constructor on
a given region in memory (object): you have to go through a new-expression
with the help of a library provided new() function that just returns its
argument and does no allocation of its own. Given all those provisions in
place, evaluation of a placement new expression boils down to nothing more
than calling a constructor. (Very much like some function call expressions
boil down to nothing more than calling a function:)


In any case, we need to know more from the OP. The creator objects I
suggestest, will not use placement new but allocate memory and return
pointers to the constructed objects. If the OP has different requirements,
he would need to tell us.


Best

Kai-Uwe Bux
 
J

James Kanze

There is also no way of "calling a function" either. All that
there is, according to the standard, is that a function call
expression is evaluated and in the course of the execution of
that evaluation, a function will be called (but sometimes more
happens: in the case of virtual functions, there might even be
some mechanism involved behind the scenes to decide which
one).

And your point is? The standard speaks of a function call
operator, and a function call expression. The expression
evaluates the arguments and calls the function. (Which function
is called, of course, depends on the expression, and a number of
other things.)

The standard doesn't have a constructor call expression. It
speaks of calling the constructor in the context of other
operations, such as type conversions, declarations or a new
expression. And all of these other operations have additional
semantics associated with them, systematically.
Similarly, there are expressions whose evaluation involves the
call of constructors (and usually much more). In fact, there
are several.
Despite this, I take the linguistic license to say that I call
a function. Also, I don't see a reason not to take the same
linguistic license with constructor calls.

Why not? The standard doesn't. I don't either, because I
think precision of expression is important when talking about
something as precise as a computer language.

Of course, if you don't care about being understood, you can use
any terminology you want.
But, actually, this terminological issue is not "more to the
point" of the OP.
This, on the other hand, is. However:
Well, C++ just provides a very very roundabout way to call a
constructor on a given region in memory (object): you have to
go through a new-expression with the help of a library
provided new() function that just returns its argument and
does no allocation of its own. Given all those provisions in
place, evaluation of a placement new expression boils down to
nothing more than calling a constructor. (Very much like some
function call expressions boil down to nothing more than
calling a function:)

Except that C++ also makes a distinction between library and
language---as far as the language is concerned, it is just
another case of an new expression.
In any case, we need to know more from the OP. The creator
objects I suggestest, will not use placement new but allocate
memory and return pointers to the constructed objects. If the
OP has different requirements, he would need to tell us.

He asked why you can't take a pointer to a constructor, like you
could a pointer to any other function. One of the reasons, of
course (not the only one), is that it makes no sense. The only
thing you can do with a pointer to a function is call the
function. Since a constructor can't be called without some
additional context, there's no practical way to implement
through a pointer to a function.

One could imagine a "pointer to a constructor", which, when
called, would also allocate memory in some way. C++ doesn't
have such, however, and if it did, it wouldn't be compatible
with a pointer to a function.
 
V

Victor Bazarov

James said:
[..] The only
thing you can do with a pointer to a function is call the
function. Since a constructor can't be called without some
additional context, there's no practical way to implement
through a pointer to a function.

Uh... You don't have to call a function once you got a pointer
to it. You may just as well compare two function pointers or
instantiate a template using the function pointer.

V
 
J

jkherciueh

James said:
And your point is? The standard speaks of a function call
operator, and a function call expression. The expression
evaluates the arguments and calls the function. (Which function
is called, of course, depends on the expression, and a number of
other things.)

The standard doesn't have a constructor call expression. It
speaks of calling the constructor in the context of other
operations, such as type conversions, declarations or a new
expression. And all of these other operations have additional
semantics associated with them, systematically.

I see that we agree on what the standard says.
Why not? The standard doesn't. I don't either, because I
think precision of expression is important when talking about
something as precise as a computer language.

Of course, if you don't care about being understood, you can use
any terminology you want.

I do not think that saying something like "here on line 27, I call the
function foo()" is misleading. That is why I take the linguistic license.
If you don't, I won't force you.

Except that C++ also makes a distinction between library and
language---as far as the language is concerned, it is just
another case of an new expression.

Yet another point of agreement: it is just an expression whose evaluation
entails nothing more than a constructor call.
He asked why you can't take a pointer to a constructor, like you
could a pointer to any other function.

No. What the OP asked is this:

Is it possible to pass a pointer to a constructor or a class definition
as argument to a function?

The OP was not interested in the reasons why you cannot take a pointer to a
constructor because he did not know that he could not (had he known that
the question he asked would be moot). Moreover, he provided some
(insufficient) background as to why he wants to pass such a constructor
pointer to the function:

The function should construct a number of objects using the given
constructor. The objects should all inherit from a base class.

It's not possible to pass actual objects, since it's not given on
beforehand, how many should be created.

None of this shows any interest in the reasons why you cannot obtain a
pointer to a constructor. Instead it indicates that the OP has some design
problem and that he would probably be interested in alternatives to the
constructor-pointer approach that (as the two of have pointed out) cannot
work directly.
One of the reasons, of
course (not the only one), is that it makes no sense. The only
thing you can do with a pointer to a function is call the
function.

Victor has already addressed that misconception. However from the context of
the OP it is morally clear that the OP actually wanted to call the
constructor.
Since a constructor can't be called without some
additional context, there's no practical way to implement
through a pointer to a function.

One could imagine a "pointer to a constructor", which, when
called, would also allocate memory in some way. C++ doesn't
have such, however, and if it did, it wouldn't be compatible
with a pointer to a function.

You are just providing additional reason as to why we need to know more
about the underlying problem that the OP is trying to solve.


Best

Kai-Uwe Bux
 
T

Tomás Ó hÉilidhe

Morten Lemvigh:
Is it possible to pass a pointer to a constructor or a class definition
as argument to a function? Maybe in a way similar to passing function
pointers...?

The function should construct a number of objects using the given
constructor. The objects should all inherit from a base class.

It's not possible to pass actual objects, since it's not given on
beforehand, how many should be created.


Instead of a getting a pointer directly to the contructor, you can get the
address of a very small function which calls the constructor:

void Func(T *const p)
{
::new(p) T(whatever parameters);
}
 
J

James Kanze

I see that we agree on what the standard says.
I do not think that saying something like "here on line 27, I call the
function foo()" is misleading. That is why I take the linguistic license.
If you don't, I won't force you.

I do myself in certain cases. I'm just worried here that it
would lead to confusion. The real issue at stake, IMHO, is that
you don't "call a constructor", but "create an object". And
creating an object consists of two phases: allocation and
initialization. The constructor is only relevant to the second,
and it's hard to see what you could do with the address if you
could take it, given that the standard doesn't really provide a
means of separating the two phases. The issues could obviously
be addressed: pointer to a constructor is a special type, user
is required to provide the memory somehow, etc. The question is
just: is it worth it? It seems like a lot of extra complexity
to me, for very little gain. And of course, at least in the
first case, pointers to constructors wouldn't be compatible with
pointers to functions.

[...]
Victor has already addressed that misconception.

With some incidental functionality. The rôle of pointers to
functions isn't to be compared.
However from the context of the OP it is morally clear that
the OP actually wanted to call the constructor.

You mean, he wanted to create an instance of the object, or?
(For some strange reason, the original posting didn't show up at
Google, and I can't see it, although it appears in the list of
the thread. It seems to be happening with a lot of postings at
the moment.)
You are just providing additional reason as to why we need to
know more about the underlying problem that the OP is trying
to solve.

Yes. In my experience, most real problems end up having a
simple and elegant solution in C++. (The complexity of the
language results in simpler user programs than with some other,
apparently simpler languages.)
 
A

Alf P. Steinbach

* James Kanze:
(For some strange reason, the original posting didn't show up at
Google, and I can't see it, although it appears in the list of
the thread. It seems to be happening with a lot of postings at
the moment.)

And vice versa -- SuperNews fails to provide a lot of postings that
show up in Google's archive, and that includes about 50% (it feels like)
of comp.lang.c++.moderated postings...

I'm wondering whether there is some too active spam-filter somewhere.


In case it helps, the original posting:

* Morten Lemvigh:
Is it possible to pass a pointer to a constructor or a class
definition as argument to a function? Maybe in a way similar
to passing function pointers...?

The function should construct a number of objects using the given
constructor. The objects should all inherit from a base class.

It's not possible to pass actual objects, since it's not given on
beforehand, how many should be created.


And as pointed out else-thread,

* Tomás Ó hÉilidhe:
Instead of a getting a pointer directly to the contructor, you can
get the address of a very small function which calls the constructor:

void Func(T *const p)
{
::new(p) T(whatever parameters);
}


I don't like having that storage argument typed as T*, but then, as I
recall the standard's default allocator class does that dirty thing too.

A more direct design is to try to translate the OP's requirements to C++.

"It's not given on beforehand, how many should be created" -> dynamic
allocation.

"The objects [to be created] should all inherit from a base class" -> a
function returning pointer to Base:

std::auto_ptr<Base> newDerived();

Also it seems it should have some arguments, perhaps just one (doesn't
matter):

std::auto_ptr<Base> newDerived( Arg const& );

Now all that's needed is to define such a function for a given
constructor of a given subclass of Base, and pass that function as
argument. If there are many such potential subclasses, the function can
be templatized in order to do this once and for all:

template< typename Derived >
std::auto_ptr<Base> newDerived( Arg const& arg )
{
return std::auto_ptr<Derived>( new Derived( arg ) );
}

So all the client code needs to do is

foo( &newDerived<MyDerivedClass> );

Cheers,

- Alf

PS: Just mentioning it, yet again, re terminology, source level
constructor "call" -> needed for standard's definition of default
constructor, + use of term "explicit constructor call" in standard and
keyword "explicit"... Do you remember discussing this before? <g>
 
J

James Kanze

* James Kanze:
And vice versa -- SuperNews fails to provide a lot of postings that
show up in Google's archive, and that includes about 50% (it feels like)
of comp.lang.c++.moderated postings...
I'm wondering whether there is some too active spam-filter somewhere.

A strange one, then, since it seems to allow a lot of real spam
through. Even stranger, the postings show up in the list of
postings in the thread, but when you click on it to view it, it
doesn't work.

[...]
PS: Just mentioning it, yet again, re terminology, source level
constructor "call" -> needed for standard's definition of default
constructor, + use of term "explicit constructor call" in standard and
keyword "explicit"... Do you remember discussing this before? <g>

Yes. I tried to avoid couching the argument in terms of what
the standard does or does not call it, since that wasn't my real
point (and I guess neither you nor I have anything new to add,
that we haven't already said several times).
 
M

Morten Lemvigh

A more direct design is to try to translate the OP's requirements to C++.
"It's not given on beforehand, how many should be created" -> dynamic
allocation.

"The objects [to be created] should all inherit from a base class" -> a
function returning pointer to Base:

std::auto_ptr<Base> newDerived();

Also it seems it should have some arguments, perhaps just one (doesn't
matter):

std::auto_ptr<Base> newDerived( Arg const& );

Now all that's needed is to define such a function for a given
constructor of a given subclass of Base, and pass that function as
argument. If there are many such potential subclasses, the function can
be templatized in order to do this once and for all:

template< typename Derived >
std::auto_ptr<Base> newDerived( Arg const& arg )
{
return std::auto_ptr<Derived>( new Derived( arg ) );
}

So all the client code needs to do is

foo( &newDerived<MyDerivedClass> );

Thanks to everyone for all the comments! (Though I think I will have to
read them a couple of more times to really understand all of them!)

It sounds to me like Alf's and Kai-Uwe suggesting could be what I need,
but since I'm new to these constructions (as You have already guessed
from my question) I'll just have to try to experiment a little.

But to restate my needs without the mention of non-existing
constructor-pointers:

I have an object (Generator), which during it's life cycle should create
a number of other objects on the heap. These objects should be of
classes that inherit from a BaseClass. What I need, is to be able to
tell the Generator what exact derived class to use.

So if I understand your suggested solution correctly, it will solve my
problem!

So thanks again!
Morten
 
L

liam

I have an object (Generator), which during it's life cycle should create
a number of other objects on the heap. These objects should be of
classes that inherit from a BaseClass. What I need, is to be able to
tell the Generator what exact derived class to use.

What you describe here is a well defined pattern called the Abstract
Factory. I have one implementation of this pattern on my website which
uses methods which have been shown in this thread.
http://liamdevine.co.uk/code/abstract_factory.php

Liam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top