POV-Ray : Newsgroups : povray.off-topic : C++ question for the experts : Re: C++ question for the experts Server Time
29 Jul 2024 20:15:08 EDT (-0400)
  Re: C++ question for the experts  
From: clipka
Date: 14 May 2011 15:41:04
Message: <4dcedad0$1@news.povray.org>
Am 14.05.2011 18:43, schrieb Darren New:
> Is it possible to put a class into a variable in C++?
>
> In particular, assume I have a superclass "Thing", with subclasses
> Alpha, Beta, Gamma. I want to instantiate one of each of the subclasses
> and put each instance into a vector.
>
> Thing* thing;
> thing = new Alpha(1,true);
> stuff.push_back(thing);
> thing = new Beta(1,true);
> stuff.push_back(thing);
> thing = new Gamma(1,true);
> stuff.push_back(thing);
>
> Is there any way to do that with only one call to new?
>
> In something like Tcl or Python, I'd do something like
>
> for x in [Alpha, Beta, Gamma] {
> thing = new x(1,true);
> stuff.push_back(thing);
> }
>
> Is there any way to do anything similar in C++?

Not out of the box; you could use a factory-based approach though, e.g.:

class Thing_Factory_Base {
public:
     virtual Thing* New(int i, bool b) = 0;
}

template<class T>
class Thing_Factory : public Thing_Factory_Base {
public:
     virtual Thing* New(int i, bool b)
         { return new T(i,b); }
}

Thing_Factory<Alpha> Alpha_Factory = new Thing_Factory<Alpha>();
Thing_Factory<Beta>  Beta_Factory  = new Thing_Factory<Beta>();
Thing_Factory<Gamma> Gamma_Factory = new Thing_Factory<Gamma>();

list = Factory_List[3] {
   Alpha_Factory,
   Beta_Factory,
   Gamma_Factory
};
for (int i = 0; i < 3; i ++)
     stuff.push_back(Factory_List[i].New(1,true));


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.