473,749 Members | 2,486 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

function pointer to constructor

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
Jan 18 '08 #1
9 23767
Morten Lemvigh wrote:
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, MyArgas 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 () );
}
};

Now, you can pass creator<MyType> ().

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
Jan 18 '08 #2
On Jan 18, 1:44 pm, jkherci...@gmx. net wrote:
Morten Lemvigh wrote:
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.
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.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 18 '08 #3
James Kanze wrote:
On Jan 18, 1:44 pm, jkherci...@gmx. net wrote:
>Morten Lemvigh wrote:
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.

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
Jan 18 '08 #4
On Jan 18, 3:11 pm, jkherci...@gmx. net wrote:
James Kanze wrote:
On Jan 18, 1:44 pm, jkherci...@gmx. net wrote:
Morten Lemvigh wrote:
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.
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).
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.
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:-)
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.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 18 '08 #5
James Kanze wrote:
[..] 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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 18 '08 #6
James Kanze wrote:
On Jan 18, 3:11 pm, jkherci...@gmx. net wrote:
>James Kanze wrote:
On Jan 18, 1:44 pm, jkherci...@gmx. net wrote:
Morten Lemvigh wrote:
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.
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).

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.
>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.
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.

>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:-)

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.
>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.
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
Jan 18 '08 #7
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);
}
--
Tomás Ó hÉilidhe
Jan 19 '08 #8
On Jan 18, 9:12 pm, jkherci...@gmx. net wrote:
James Kanze wrote:
On Jan 18, 3:11 pm, jkherci...@gmx. net wrote:
James Kanze wrote:
On Jan 18, 1:44 pm, jkherci...@gmx. net wrote:
Morten Lemvigh wrote:
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.
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).
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.
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.
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.

[...]
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.
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.)
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.
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.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 19 '08 #9
On Jan 19, 1:34 pm, "Alf P. Steinbach" <al...@start.no wrote:
* 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++.m oderated 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
in articles by Bjarne Stroustrup and Andrew Koenig, +, of course,
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).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 20 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2252
by: firegun9 | last post by:
Hello everyone, here is my program: /////////////////////////////// #include <iostream> using namespace std; void multi(double* arrayPtr, int len){ for(int i=0; i<len; i++) *(arrayPtr+i)*=2;
6
1238
by: Peter Oliphant | last post by:
Here is a simplification of my code. Basically, I have a class (A) that can be constructed using a function pointer to a function that returns a bool with no parameters. I then want to create an instance of this class (A) in another class (B) which uses one of its own methods of the 'proper form' to initialize the instance. But I get an error: __gc class ClassA { public: ClassA( bool (*func)(void) ) {//---some code---//} // constructor
10
15181
by: ChrisB | last post by:
Coming from a C/C++ background, how would I pass a function pointer to a function? I want to write a function that handles certain thread spawning. Here's what I'm trying to invision: function( thesub as <functionptr?> ) dim t as new system.threading.thread( _ new system.threading.threadstart( Addressof thesub )) .... How can I get something like that going in VB.Net?
23
7818
by: bluejack | last post by:
Ahoy... before I go off scouring particular platforms for specialized answers, I thought I would see if there is a portable C answer to this question: I want a function pointer that, when called, can be a genuine no-op. Consider: typedef int(*polymorphic_func)(int param);
9
5923
by: Allen | last post by:
Hi, I want to know How to create an associated array using map with keys are string, values are function pointers with same arguments, but each function belong to different class. The map need to be initialized static, what's the syntax to retrieve a function pointer?
6
4154
by: Caleb | last post by:
I have a class that has two member functions of the same name: class MyClass { public: void someFunction(int arg); void someFunction(int arg, char blah); }; I'm trying to get a tr1::functional to the first one, for example:
20
2237
by: MikeC | last post by:
Folks, I've been playing with C programs for 25 years (not professionally - self-taught), and although I've used function pointers before, I've never got my head around them enough to be able to think my way through what I want to do now. I don't know why - I'm fine with most other aspects of the language, but my brain goes numb when I'm reading about function pointers! I would like to have an array of structures, something like
4
4400
by: Immortal_Nephi | last post by:
I had a lot of research to see how function pointer works. Sometimes, programmers choose switch keyword and function in each case block can be called. Sometimes, they choose ordinary function pointer array instead of switch. They believe that ordinary function pointer is much faster than switch. Think of one variable called selectFunction. selectFunction variable can be the range of 0 through 1,000 or more. Load selectFunction...
2
2865
myusernotyours
by: myusernotyours | last post by:
Hello everyone. I am using a C library from C++ code. The C library declares some function pointers using typedef, and then makes some variables using this function pointer as the type. Like: typedef void (*func) (int); //then the pointer... func ptr; For me to work with this library I need to assign one of my member functions to the library variable(the func pointer) above.
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9566
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9388
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9333
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6800
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3319
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.