Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Is there a similar easy way to achieve this in C++?

I'm using Visual Studio 2010, if that's important.

[Update]: Remember, there is a very important difference between casting and using as . Casting (at least in C#) will throw an exception if the type does not match:

Object o = null;
String s = (String)o; // Will crash.
                None of the answers suggesting using dynamic_cast are correct.  The C# keyword is a conversion operation, but dynamic_cast is a cast.
– John Dibling
                Jun 14, 2010 at 15:47
                @sylvanaar:  According to the C# spec, the cast operator and the as keyword both perform conversions.  See 7.9.11 and 7.6.6
– John Dibling
                Jun 14, 2010 at 16:30
                @John, they might technically not be 100% identical, but this was 100% what I was looking for, and it is working flawlessly.
– Sam
                Jun 15, 2010 at 7:54

In C++, this would be a dynamic_cast, if you had a hierarchy where Object is the parent and String is the child.

Object * p = createMyObject();
String * s = dynamic_cast<String *>(p);
if(s)

Dynamic casting a pointer will return a pointer to the object if the cast is possible, or a null pointer if not.

Also, dynamic casting a reference will return a reference to the object if the cast is possible, or throw an exception.

Your syntax is wrong. should be: dynamic_cast<String*>(p); and you should note that String must be derived from Object. – anon Jun 14, 2010 at 10:06 As an extension to what Neil said, there is no common base class that all classes in C++ automatically derive from. Some libraries do have such a central class, like Qt and wxWidgets, but these are explicitly derived from, either directly or through another class. – blwy10 Jun 14, 2010 at 10:14

In C++ there is no base object class, so in general there is no way of doing this. You can however do it for specific hierarchies:

struct A {
   virtual ~A() {}
struct B : public A {
A * p = Something();     // Something() may return an A * or a B *
B & b = dynamic_cast <B&>(*p);

The dynamic cast will throw an exception if p does not point at something that can safely be converted to a B reference.

We should note the differences of casting a reference to casting a pointer. If the dynamic_cast fails: on a pointer then NULL is returned; on a reference an exception is thrown – Martin York Jun 14, 2010 at 12:28 With pointers, you get a null pointer if the cast is invalid. It works with references, but throws an exception if invalid. – Pontus Gagge Jun 14, 2010 at 10:03 Considering this from the c# programmer's reference: The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. And: expression as type is equivalent to: expression is type ? (type)expression : (type)null. I'd say the as operator is most resembling the dynamic_cast especially since as cannot perform user-defined conversions. – Tommy Andersen Jun 14, 2010 at 17:59 I understand this, but the question is about an equivalent operation in C++, so even though it is not important to distinguish between 'cast' and 'convert' in a language like C#, there is a big difference in C++. So it is important to be clear. You said yourself, "as is like a cast" -- not "as is as cast." And the C# spec is equally explicit: (7.6.6) : "A cast-expression is used to explicitly convert an expression to a given type" and (7.9.11) : "The as operator is used to explicitly convert a value to a given reference type or nullable type" These are conversions, not casts. – John Dibling Jun 14, 2010 at 20:40 An interesting note on the as keyword from the MSDN: C# for C++ Developers: The as keyword is similar to a standard cast, except that rather than throw an exception if the conversion fails, the return value is null. This is similar to using static_cast in C++, which, unlike dynamic_cast, performs no run-time check and hence does not throw an exception on failure. – Tommy Andersen Jun 14, 2010 at 22:14

In C# the as keyword converts a value to another type. There is code that supports this conversion (probably in the C# runtime). This is not a cast.

For the most part you can't use dynamic_cast or any other kind of cast in C++ to accomplish this, because casts and conversions are not the same thing. I say 'for the most part' because some types can be converted using static_cast, to convert an int to a float but this is still a conversion, not a cast. Also, if you have introduced a type system where everything is derived from an Object-like base class that has this conversion functionality, you might be able to construct a mechanism to support this conversion using dynamic_cast, but you would have had to write this mechanism and this does not seem to be what you're trying to do.

There is nothing built-in to C++ which will do this conversion for you; in other words, there is no C++ equivalent to the C# as keyword.

If you want to perform this conversion, you can often use streams:

#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
    float f = 42.0f;
    stringstream ss;
    ss << f;
    string s = ss.str();
    cout << "Float: " << f << ", String '" << s << "'";
    return 0;

<sstream> is part of the C++ Standard, so in this regard you might consider it to be 'in the language'.

Using streams to do this conversion can be rather clumsy. Boost offers lexical_cast which can be used to perform these simple conversions with less code:

#include <sstream>
#include <iostream>
#include <boost\lexical_cast.hpp>
using namespace std;
int main()
    string s = "42";
    float f = boost::lexical_cast<float>(s);
    cout << "Float: " << f << ", String '" << s << "'";
    return 0;
                @sylvanaar:  In C# there seems to be no such thing as a true 'cast' in the C++ sense.  In C++ a cast means "pretend variable x is of type Y", but according to the C# spec, (7.6.6) "A cast-expression is used to explicitly convert an expression to a given type." and (7.9.11) "The as operator is used to explicitly convert a value to a given reference type or nullable type. Unlike a cast expression (§7.6.6), the as operator never throws an exception. Instead, if the indicated conversion is not possible, the resulting value is null."
– John Dibling
                Jun 14, 2010 at 16:26
                @sylvanaar:  If you downvoted my answer, you must think it is wrong.  What, exactly, is wrong in my post?
– John Dibling
                Jun 14, 2010 at 16:28
                Why is using As on a reference type in c# not the same as using dynamic_cast on a pointer in C++? MS does mix their terms a little but the c# spec says "The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception" I don't think you are correct in drawing such a strong distinction between cast/convert in this instance. But ill remove my downvote - just edit your post
– sylvanaar
                Jun 14, 2010 at 20:28
                @sylvanaar: The downvote isn't the issue.  The correctness of as being a cast is what I'm taking issue with here.  The spec is explicit: (7.6.6) : "A cast-expression is used to explicitly convert an expression to a given type" and (7.9.11) : "The as operator is used to explicitly convert a value to a given reference type or nullable type" These are conversions, not casts.
– John Dibling
                Jun 14, 2010 at 20:41
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.