Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > selecting a type at run time?

Reply
Thread Tools

selecting a type at run time?

 
 
Phlip
Guest
Posts: n/a
 
      09-28-2007
aaragon wrote:

> dim = read(filename);
> if(dim == 2)
> G2D* g_ = new G2D();
> else if (dim == 3)
> G3D* g_ = new G3D();
>
> // then use g_ to whatever is needed


Google for the Factory Pattern in C++.

--
Phlip
http://www.oreilly.com/catalog/9780596510657/
^ assert_xpath

 
Reply With Quote
 
 
 
 
aaragon
Guest
Posts: n/a
 
      09-28-2007
Hi everyone,

Probably the solution to this question is trivial but I couldn't find
a clean way to do it. I try to have a variable depending on a
parameter that is read from a file at run time. Let's say something
like this:

....

dim = read(filename);
if(dim == 2)
G2D* g_ = new G2D();
else if (dim == 3)
G3D* g_ = new G3D();

// then use g_ to whatever is needed
....

The only way I managed to do this, is to have two pointers in the
code...=/
Is there a better approach? Thank you,



 
Reply With Quote
 
 
 
 
Rolf Magnus
Guest
Posts: n/a
 
      09-29-2007
aaragon wrote:

> Hi everyone,
>
> Probably the solution to this question is trivial but I couldn't find
> a clean way to do it. I try to have a variable depending on a
> parameter that is read from a file at run time. Let's say something
> like this:
>
> ...
>
> dim = read(filename);
> if(dim == 2)
> G2D* g_ = new G2D();
> else if (dim == 3)
> G3D* g_ = new G3D();
>
> // then use g_ to whatever is needed
> ...
>
> The only way I managed to do this, is to have two pointers in the
> code...=/
> Is there a better approach?


Yes. Use polymorphism. Derive G2D and G3D from a polymorphic base class.



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Run-time template list definition / Run-time variable type definition Pierre Yves C++ 2 01-10-2008 02:52 PM
selecting and working with appropriate data type lane straatman C Programming 13 01-09-2007 06:55 PM
Re: Type casting- a larger type to a smaller type heyo C Programming 3 04-01-2004 06:35 PM
Selecting implicit type conversions? Simon Leonard C++ 1 11-06-2003 05:46 PM
Portably Selecting an Integer Type of a Specific Size? Simon G Best C++ 3 07-17-2003 07:58 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57