[net.lang.c++] address of constructor

keith@cecil.UUCP (keith gorlen) (04/01/86)

Is there a way to get the address of a constructor function in C++?

-- 
---
	Keith Gorlen
	Computer Systems Laboratory
	Division of Computer Research and Technology
	National Institutes of Health
	Bethesda, MD 20892
	phone:	(301) 496-5363
	uucp:	{decvax!}seismo!elsie!cecil!keith

bs@alice.UucP (Bjarne Stroustrup) (04/03/86)

> Subject: Address of constructor
> Path: ..!cecil!keith (keith gorlen @ NIH-CSL, Bethesda, MD)
> 
> Is there a way to get the address of a constructor function in C++?

No. Why do you want it? To pass a function that constructs an object?
If so, this trick can be used:

class base { ... };
class x : public base { ... x(int); };
class y : public base { ... y(int); };

typedef base* (*PF)(int);

some_function(PF f) {
	// ...
	base* p = (*f)(2);	// name a new x or y
	// ...
}

base* xtor(int i) { return new x(i); }
base* ytor(int i) { return new y(i); }

another_function()
{
	some_function(&xtor);
	some_function(&ytor);
}

A slightly more elegant version would involve pointers to member functions.
Note that destructors can be virtual so that you don't have to play games
with pointers to functions to get proper cleanup.

cudcv@daisy.warwick.UUCP (Rob McMahon) (04/07/86)

In article <5241@alice.uUCp> bs@alice.UUCP writes:
>
>typedef base* (*PF)(int);
>
>some_function(PF f) {
>	// ...
>	base* p = (*f)(2);	// name a new x or y
>	// ...
>}
>

That reminds me - why do I have to say

typedef int (*PF)(int);
int f ( PF f1 ) { ; }

when I mean

int f ( int (*f1)(int) ) { ; }

which says

"xx.c", line 1: error: syntax error

four times.  I don't want to create a new typedef which I am going to use
once, particularly when writing an include file for others to use, so that
I have to use some obscure name to avoid conflicts.
-- 
UUCP:   ...!mcvax!ukc!warwick!cudcv
JANET:  cudcv@uk.ac.warwk.daisy
ARPA:   cudcv@daisy.warwk.ac.uk
PHONE:  +44 204 523037
Rob McMahon, Computer Unit, Warwick University, Coventry CV4 7AL, England