Topic: typeid operator and new
Author: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
Date: Tue, 31 Aug 1993 05:14:40 GMT Raw View
mbr@bellcore.com (Mark Rosenstein) writes:
>Reading through "Standard C++ Update" in the July/August issue of C++
>report, it wasn't clear whether it would be possible to use the
>run-time type identification extension to dynamically allocate objects
>of dynamically determined type.
[reformatted for brevity:]
>class employee { ... };
>class programmer : public employee{ ... };
>
>is there a way to do:
>
employee *pe;
>employee *fred = new typeid(*pe);
>
>[obviously this is not a reasonable syntax, but what I want is fred to
>a new programmer.]
There couldn't be a way of doing this directly, because not all employees
can be created from scratch using the default constructor - you may
need to pass some parameters to the constructor, and these parameters
may be different for each different derived class.
You can achieve the desired effect by using a virtual function make()
such as
employee* employee::make() { return new employee; }
employee* programmer::make() { return new employee; }
fred = pe->make();
(If employee is an abstract base class then employee::make() should be
pure virtual).
--
Fergus Henderson fjh@munta.cs.mu.OZ.AU
Author: mbr@bellcore.com (Mark Rosenstein)
Date: 27 Aug 93 11:12:57 Raw View
Reading through "Standard C++ Update" in the July/August issue of C++
report, it wasn't clear whether it would be possible to use the
run-time type identification extension to dynamically allocate objects
of dynamically determined type.