Re: Run-time creation of an object of a dynamically determined class
Kodi Arfer wrote:
Suppose I've got a base-class pointer which is pointing to an object
that belongs to any of a number of derived classes.
[...]
struct Barney
{Barney() {};
virtual void greeting() {cout << "Barney says hello.\n";};};
struct Dave : public Barney
{Dave() {};
virtual void greeting() {cout << "Dave says hello.\n";};};
struct Dan : public Barney
{Dan() {};
^
virtual void greeting() {cout << "Dan says hello.\n";};};
^
Just for your info: the marked semicolons are redundant. ;)
void funkshun()
{Barney *bp1 = &ADaveOrADan;
Barney *bp2;
...}
Now, suppose I want to make bp2 point to a new, dynamically allocated
object; not just any object, but one of the same class as *bp1.
No problem, invoke a so-called "virtual copy constructor" or "clone
function":
class base {
virtual base* clone() const = 0;
};
class derived {
virtual derived* clone() const {
return new derived(*this);
}
};
....or use the so-called "factory pattern".
The thing is, so far as I understand (I'm still more or less a C++
newbie; please bear with me here), the new operator's first argument,
the type of object to be created, must be known at compile-time.
Right.
Failing some way to really do what I'd like to do, with a method that
universally works, one workaround occurs to me. I could have Barney
define a virtual "newobj" method, which would be redefined in each
derived class to simply call "new [derived class]". But having each
and every derived class refer to itself in the third person (so to
speak) in that way seems inelegant.
True, but I'm afraid there's no other way. In fact it is one of the big
criticisms of C++ that it doesn't have any way to inspect types at either
compile time or runtime. The only thing it supports is checking if two
objects have the same type, but that is already all.
I suppose it would be a bit of an improvement to have a simple
template class from which each derived class would inherit like so:
struct Dave : public Barney, public SelfCopier <Dave>
but that's not _much_ of an improvement.
Using the CRTP seems a bit of overkill and also doesn't work that easily.
The problem is that you can't satisfy a baseclass' pure virtual function by
simply inheriting another class that has a suitable memberfunction. For
that to work, I think that both would have to derive virtually from a
common base.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Michael W?hrmann, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]