selecting a type at run time?

Discussion in 'C++' started by Phlip, Sep 28, 2007.

  1. Phlip

    Phlip Guest

    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
    Phlip, Sep 28, 2007
    #1
    1. Advertising

  2. Phlip

    aaragon Guest

    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,

    aaragon, Sep 28, 2007
    #2
    1. Advertising

  3. Phlip

    Rolf Magnus Guest

    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.
    Rolf Magnus, Sep 29, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Cook
    Replies:
    0
    Views:
    433
    Paul Cook
    Nov 6, 2003
  2. Tzury Bar Yochay
    Replies:
    3
    Views:
    473
    Jacob Yang [MSFT]
    Nov 29, 2003
  3. =?Utf-8?B?cmtibmFpcg==?=

    Design Time vs Run Time DataGrid

    =?Utf-8?B?cmtibmFpcg==?=, Feb 1, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    584
    Karl Seguin
    Feb 1, 2005
  4. flamesrock
    Replies:
    8
    Views:
    430
    Hendrik van Rooyen
    Nov 24, 2006
  5. Pierre Yves
    Replies:
    2
    Views:
    468
    Pierre Yves
    Jan 10, 2008
Loading...

Share This Page