If all of the objects you would be returning are derived from a common base class, you could use a std::map<std::string,BaseClass *>. The comparisons ultimately in there somewhere, but it keeps things better organized.

Answer from jonsca on Stack Overflow
Discussions

C++ experts - implicit conversion of String to C-string?
The String class has the c_str() method to convert to a const char*. However, this means we have lots of duplicated APIs in the code, e.g. void Spark.subscribe(const char* eventName, ...); and void Spark.subscribe(String eventName, ...) { Spark.subscribe(eventName.c_str(), ...); } With the ... More on community.particle.io
🌐 community.particle.io
7
4
April 24, 2015
Converting String to Cstring in C++ - Stack Overflow
I have a string to convert, string = "apple" and want to put that into a C string of this style, char *c, that holds {a, p, p, l, e, '\0'}. Which predefined method should I be using? More on stackoverflow.com
🌐 stackoverflow.com
c++ - How to convert a string to a class name - Stack Overflow
1001 Why should C++ programmers minimize use of 'new'? 575 How to convert an enum to a string in modern C++ More on stackoverflow.com
🌐 stackoverflow.com
March 27, 2011
c++ - Converting class to string - Stack Overflow
gotw3.cc:17:9: error: C++ requires ... string::string(const Employee& e) ~~~~~~ ^ ... If you are trying to overload the casting, this link may help: learncpp.com/cpp-tutorial/910-overloading-typecasts ... Two things: first, you cannot add to an existing class without modifying the class definition. If you have a class that you want convertible to std::string ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 4
3

C++ doesn't have any introspection so no it's not possible.

However, you can "hack" it by having another std::map that contains the names as keys, and the value is a reference to the variable:

agnt temp;

std::unordered_map<char, int&> variable_map = {
    { 'x', temp.x },
    { 'y', temp.y }
};

variable_map['x'] = 123;
std::cout << variable_map['y'] << '\n';

It's generally not worth it though, as it more work. Especially if you want to do this for multiple variables (as each structure variable needs its own mapping).

2 of 4
1

You can't do this in C++ because it's a statically-typed language. One way to get this sort of behaviour is to provide accessing wrappers:

template <char c>
struct getter {
};


template <>
struct getter<'x'> { 
   static int get(const agnt &theAgnt) {
      return theAgnt.x;
   }
};


template <>
struct getter<'y'> { 
   static int get(const agnt &theAgnt) {
      return theAgnt.y;
   }
};

template <char c>
int get(const agnt &theAgnt) {
    return getter<c>::get(theAgnt);
}

And call like:

agnt temp;
//... set members
std::cout << get<'x'>(temp) << std::endl;

However, the for loop won't work the way you expect, because the template parameters need to be determined at compile time. Also, you can't just request any old thing, unless you define a get function in the unspecialised getter which returns some sort of NULL-indicator, like INT_MIN.

However, this is all really a hack to get something vaguely similar to a dynamic language. But it's not really anything different from just referencing temp.x. Instead, you should try to adhere to C++ conventions and enjoy the static typing!

🌐
Bham
epweb2.ph.bham.ac.uk › user › hillier › course3cpp › howto › cstrings.html
Converting data to C++ and C-style strings
The most general way of making a C-string from anything that can be output with the << insertion operator is to use a function like this (shorter solutions welcomed): #include <sstream> // Convert to C-string.
🌐
Particle
community.particle.io › firmware
C++ experts - implicit conversion of String to C-string? - Firmware - Particle
April 24, 2015 - The String class has the c_str() ...cribe(eventName.c_str(), ...); } With the String api simply unwrapping the string to a C-string and calling the C-string function....
Top answer
1 of 5
10

You can create a simple factory and register the classes you want to be able to construct. This is a very light-weight sort-of reflection.

#include <map>
#include <string>

template <class T> void* constructor() { return (void*)new T(); }

struct factory
{
   typedef void*(*constructor_t)();
   typedef std::map<std::string, constructor_t> map_type;
   map_type m_classes;

   template <class T>
   void register_class(std::string const& n)
   { m_classes.insert(std::make_pair(n, &constructor<T>)); }

   void* construct(std::string const& n)
   {
      map_type::iterator i = m_classes.find(n);
      if (i == m_classes.end()) return 0; // or throw or whatever you want
      return i->second();
   }
};

factory g_factory;

#define REGISTER_CLASS(n) g_factory.register_class<n>(#n)

int main()
{
   using namespace std;

   REGISTER_CLASS(string);

   std::string* s = (std::string*)g_factory.construct("string");

   printf("s = '%s'\n", s->c_str());
   *s = "foobar";
   printf("s = '%s'\n", s->c_str());

   return 0;
}
2 of 5
1

What you want is called virtual constructor (pattern). The availability of this feature in a language is not necessarily coupled to the language being interpreted or managed by a VM - it depends on how (and if at all) the information about types existing in a program (or library) is available at run time. This is not the case in "naked" C++ - but it can be implemented, as shown by Arvid, for example. The problem is that there is no standardized implementation of this feature, so everybody keeps re-inventing this again and again. To certain extent COM or it's platform independent counterpart XPCOM "standardize" this at component level.

Find elsewhere
Top answer
1 of 9
33

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

2 of 9
32

Much easier way of doing it: you will need com.google.gson.Gson for converting the object to json string for streaming

to convert object to json string for streaming use below code

Gson gson = new Gson();
String jsonString = gson.toJson(MyObject);

To convert back the json string to object use below code:

Gson gson = new Gson();
MyObject = gson.fromJson(decodedString , MyObjectClass.class);

Much easier way to convert object for streaming and read on the other side. Hope this helps. - Vishesh

Top answer
1 of 3
4

You can get a C++ std::string from the stream's str() function, and an immutable C-style zero-terminated string from the string's c_str() function:

std::string cpp_string = str.str();
char const * c_string = cpp_string.c_str();

You might be tempted to combine these into a single expression, str.str().c_str(), but that would be wrong; the C++ string will be destroyed before you can do anything with the pointer.

What you are doing will work, as long as you're sure that the buffer is large enough; but using the C++ string removes the danger of overflowing the buffer. In general, it's best to avoid C-style strings unless you need to use an API that requires them (or, in extreme circumstances, as an optimisation to avoid memory allocation). std::string is usually safer and easier to work with.

2 of 3
2

Unless you have a specific reason that you need an array of char instead of a standard string, I'd use the latter. Although it's not strictly necessary in this case, I'd also normally use a Boost lexical_cast instead of explicitly moving things through a stringstream to do the conversion:

std::string zipString = lexical_cast<std::string>(zip);

Then, if you really need the result as a c-style string, you can use zipString.c_str() to get that (though it's still different in one way -- you can't modify what that returns).

In this specific case it doesn't gain you a lot, but consistent use for conversions on this general order adds up, and if you're going to do that, you might as well use it here too.

🌐
Florida State University
cs.fsu.edu › ~myers › cop3330 › notes › strings.html
Strings: C-strings vs. strings as objects
Use dynamic allocation and resizing to get flexible capacity · Do all dynamic memory management inside the class, so the user of string objects doesn't have to! Use operator overloads if more intuitive notations are desired ... Build copy constructor and assignment operator to for correct assignment and pass-by-value abilities · Build a conversion constructor to convert c-style strings to string objects, for automatic type conversions!
🌐
Quora
quora.com › How-do-I-convert-an-std-string-to-a-C-string-in-C
How to convert an std::string to a C string in C++ - Quora
Answer (1 of 7): All other answers only mention std::string::c_str() but there is also an accessor for the non-const pointer to the underlying string: std::basic_string::data - cppreference.com Since C++11 it has the same behavior as c_str() except for the const qualifier. It explicitly allows ...
🌐
DEV Community
dev.to › danochoa › string-conversion-approaches-in-c-3a5o
C++ String Conversion Guide - DEV Community
March 5, 2025 - C++ string classes (std::string, std::stringstream) follow the Resource Acquisition Is Initialization (RAII) principle, automatically managing memory: void convert_number() { std::string str = std::to_string(42); // No need to manually free memory } // str's destructor automatically releases memory when it goes out of scope ·
🌐
Unity
discussions.unity.com › questions & answers
How do i convert a String into a Class reference in C# - Questions & Answers - Unity Discussions
January 12, 2011 - I have the String className and i want to convert it to a class reference. what function do i use? for example: new whateverFunction("Class1")(); would be the same as: new Class1(); Is this possible?
🌐
Cplusplus
cplusplus.com › forum › general › 268772
How to convert an object to a string? - C++ Forum
So let's say that we have a class called Date for example. And you want to convert an object of a date to a string, so you can do this:
🌐
GeeksforGeeks
geeksforgeeks.org › c language › how-to-convert-c-style-strings-to-stdstring-and-vice-versa
How to convert C style strings to std::string and vice versa? - GeeksforGeeks
July 6, 2017 - This is a std::string : Testing This is a C-String : Testing Both C strings and std::strings have their own advantages. One should know conversion between them, to solve problems easily and effectively. Related articles: C++ string class and its applications | Set 1 C++ string class and its ...
🌐
Quora
quora.com › How-does-one-convert-from-string-to-c_string-Could-somebody-give-me-an-example
How does one convert from string to c_string? Could somebody give me an example? - Quora
Answer (1 of 2): The [code ]c_str() [/code]member function return a [code ]const char*[/code] to the string internal buffer, that is granted to be null terminated at least upon its call (c++98) or always (c++11). You will not own the string data through that pointer, but -as far as the std::stri...
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › text › how-to-convert-between-various-string-types
How to: Convert Between Various String Types | Microsoft Learn
October 3, 2022 - Several string types, including wchar_t *, implement wide character formats. To convert a string between a multibyte and a wide character format, you can use a single function call like mbstowcs_s or a constructor invocation for a class like CStringA.
Top answer
1 of 3
2

If you don't wish to modify the source project that RemoteFileDP lives in (or can't) you could write an extension method such as below:

public static RemoteFileDP ConvertToRemoteFileDP(this string location)
{
    // Somehow create a RemoteFileDP object with your 
    // location string and return it
}

That way you could run the line of code you want:

RemoteFileDP remoteFile = locationDirectory;

With a slight modification as follows:

RemoteFileDP remoteFile = locationDirectory.ConvertToRemoteFileDP();

Would this allow you to solve your problem?

2 of 3
2

Although I like the idea of a constructor accepting a string more, you could define an implicit or explicit conversion operator between RemoteFileDP and string:

 class RemoteFileDP
 {
      ....

      public static implicit operator RemoteFileDP(string locationDictionary)
      {
           //return a new and appropiately initialized RemoteFileDP object.
           //you could mix this solution with Anna's the following way:
           return new RemoteFileDP(locationDictionary);
      }
 }

This way you could actually write:

 RemoteFileDP remoteFile = locationDirectory;

or, if the conversion operator were to be explicit:

 RemoteFileDP remoteFile = (RemoteFileDP)locationDirectory;

Still I insist, Anna Lear's solution is better as implicit or explicit conversion doesn't really seem to be the best fit for this kind of case. For instance, if the conversion can fail due to an invalid locationDictionary value then I wouldn't recommend this path. If the conversion is always succesful no matter what value locationDictionary is (barring null) then it could be a valid solution to your problem.

I'm just putting it on the table as I think you might find it useful to know about explicit and implicit conversions in C#, in case you didn't already.