CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jun 2009
    Posts
    4

    class from string

    Hey,

    So let's not get into the potential ridiculousness of what I'm doing. But essentially I have a string that is the name of a class, I want it to create a new object of that type.

    So if I pass it a string "ClassyFace", it'll create a new ClassyFace object, if the string is "ClassyPants", I want it to make a ClassyPants object. I realise I can achieve this with a bunch of if statements but I'd like to have it go directly from the string. Also, if it helps, all of these objects share a base class.

    Any help is appreciated.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: class from string

    Personally, I would just go with an if else chain. C++ does not have a reflection feature, at least not natively.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Re: class from string

    Yes, make a factory class/method that creates the objects base on the name of the class given as string.
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

  4. #4
    Join Date
    Jun 2009
    Posts
    4

    Re: class from string

    Yeah, that's what I thought. Silly C++. Not being java :P

  5. #5
    Join Date
    Nov 2006
    Posts
    1,611

    Re: class from string

    Yeah, that's what I thought. Silly C++. Not being java :P
    Are you hear to publish points of disagreement? If you know and like Java, why are you trying your hand at C++?

    French isn't silly because it's not German, or English. C++ wasn't created to satisfy the interests of Java developers, it usually serves rather different purposes, though there can be considerable overlap.

    There's a book from Alexandrescu on the subject of metaprogramming (typelists specifically in this case) which can be used to create a simple template function which could do what you ask.
    Last edited by JVene; August 5th, 2009 at 07:57 PM.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured