0

I have recently started to learn c++ on my own and I have some prior knowledge of Java.I was wondering is there an option to typecast in c++.

Like in java char ch=(char)(65); would store 'A' in ch or int n='a'; would store 97 in n

Does c++ have same or similar options?

APE
  • 37
  • 4
  • 3
    Oh boy you gonna be surprised. – Timo Feb 12 '20 at 16:01
  • 2
    You mean an [explicit type conversion](https://en.cppreference.com/w/cpp/language/explicit_cast)? – gabriel.hayes Feb 12 '20 at 16:02
  • I hope every language can cast types – RoQuOTriX Feb 12 '20 at 16:03
  • 2
    Or [implicit conversion](https://en.cppreference.com/w/cpp/language/implicit_conversion)? – Timo Feb 12 '20 at 16:03
  • @user1538301 Both – APE Feb 12 '20 at 16:03
  • 5
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Feb 12 '20 at 16:04
  • @NathanOliver If you have any recommendations for good c++ books do tell. – APE Feb 12 '20 at 16:06
  • @APE Check the link in my comment. It's got plenty. – NathanOliver Feb 12 '20 at 16:06
  • 1
    @APE blue underlined text are links, you can click on them ;) – 463035818_is_not_an_ai Feb 12 '20 at 16:07
  • here are some more: [help], [tour], please take some time to read it – 463035818_is_not_an_ai Feb 12 '20 at 16:11
  • 1
    Side note: *char ch=(char)(65); would store 'A' in ch* is not necessarily true. It requires the character encoding to be ASCII and because C++ needs to support a staggering array of different systems this isn't always true. You'll get away with assuming ASCII the majority of the time, but this only makes it hurt more when you find a system that isn't using ASCII. Always prefer the `int n='a'` option. In addition the intent of the code is better advertised to readers if you use the character. Make code easier to read and you make it harder for bugs to hide. – user4581301 Feb 12 '20 at 16:18
  • Earlier question [casting-int-to-char-using-c-style-casting](https://stackoverflow.com/questions/16899055/casting-int-to-char-using-c-style-casting) – y_ug Feb 12 '20 at 18:18

3 Answers3

2

C++ has casts. C-style casts () (avoid them), static_cast, dynamic_cast, reinterpret_cast (be very careful), const_cast (only very rarely the right choice), std::dynamic_pointer_cast, std::forward (yes, that's a cast), std::move (yes, that's also a cast).

C++ is not Java. Don't expect much of your Java knowledge to carry over. In many cases the two languages have constructs that look the same at the source code level but do very or subtly different things. They also use a lot of common terminology, but what is meant by a term in one language can be different in the other.

There are also implicit conversions, converting constructors and conversion operators.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • I don't think the OP needs to know all that *doesn't apply* - for his/her example, all that is needed is to know about static_cast and a little later perhaps dynamic_cast. If they're starting off by trying to replicate some Java behavior, you certainly don't need to lose sleep about std::forward or or std::reinterpret_cast for example. – Dave Doknjas Feb 13 '20 at 14:33
2

For a first transition to C++, you'll be fine most of the time with static_cast for explicit conversions:

int i = static_cast<int>('c');

Of course there are also implicit conversions:

int i = 'c';
char c = 32;

And special promotion rules

char a = 'a', b = 'b';
auto result = a + b;    // result is int now

Then there are the other cast operators:

  • dynamic_cast to cast from base to derived types.
  • reinterpret_cast to make your code fail - sometimes - and you don't know why.
  • const_cast to remove constness from expressions (but only if they are not const, that is).
Timo
  • 9,269
  • 2
  • 28
  • 58
  • You forgot a few. See my answer. – Jesper Juhl Feb 12 '20 at 16:11
  • @JesperJuhl Technically they all boil down to the 4 I listed, but I get your point. Although, you're also missing conversion operators. – Timo Feb 12 '20 at 16:17
  • 1
    Thanks. I added a little blop mentioning what I missed. – Jesper Juhl Feb 12 '20 at 16:21
  • @JesperJuhl I am pleased with your sacrifice. Darn it, why did you change your comment :D – Timo Feb 12 '20 at 16:23
  • 1
    Technically not everything boils down to those four. C-style casts can do one trick that C++ casts cannot. They ignore accessibility and can thus cast to private base classes. For example: `class A {}; class B : private A {}; B b; A* p = (A*)(&b);` is valid and you cannot do that in a valid manner with any of the C++ casts. – Jesper Juhl Feb 12 '20 at 17:20
  • @JesperJuhl oh wow I didn't know that. I thought the C-style cast was purely a composition of the c++ casts. – Timo Feb 12 '20 at 18:53
  • It *is* a rather obscure corner case, admitted, and you probably don't even want to do that in the first place, but there are rare and obscure cases where it can be your only non-UB way out of a situation ;) – Jesper Juhl Feb 12 '20 at 19:17
0

C++ has several different cast operators that are used to access memory objects and each of these has differences in how they operate. In order to understand casting in C++ you need to understand the differences between these different casting methods and why you would use one or the other.

However first you must understand two fundamental differences between Java and C++ when it comes to how variables and objects are allocated and stored in memory.

The most fundamental difference between the two languages is the compile target for the two languages. Java is compiled into byte code and runs on a virtual machine. C++, most often, is compiled into native machine code and runs on the actual hardware using the hardware facilities such as CPU registers.

I used the caveat of "most often" for C++ because there are compilers, the Microsoft Visual Studio has such an option, that will generate byte code that runs on a virtual machine. However in most instances C++ is compiled to native, hardware machine code.

The second major difference between the two is how objects and variables and classes are stored and managed, how assignment works, and what kinds of information is available at runtime about the objects and variables and classes.

Java has a central memory store where objects are allocated with the new operator. This means that a Java variable is not a physical storage area containing the object but rather a physical storage area that contains a reference which points to the actual storage area in the central memory store.

This central storage area contains not only the memory area for the actual objects but also information about the classes from which the objects are instantiated. In other words much of the type information available in the source code at compile time is also available to the virtual machine in which the program is running allowing the virtual machine to determine if a cast is valid at runtime when the conversion is being done.

C++ variables are memory areas where the value of the variable or object is actually stored. C++ has pointer variables which contain the address of the memory area where an object is stored and it has reference variables which contain a reference to the address of the memory area where an object is stored. However when you are accessing a C++ object or variable with the name of the object or variable, you are accessing the memory area of the object directly and not through a reference the way it is done in Java.

So an assignment statement in Java which assigns one object to another is really just making a copy of the reference rather than the actual object. This is why after doing an assignment you now have two variables pointing to the same thing. An assignment statement in C++ which assigns one object to another is making a copy of the actual object itself into another memory area which results in two copies of the same object.

The C++ language and compilers are designed to do validity checking when the source code is compiled and to remove much of the overhead involved in the checking that the Java virtual machine does. So the C++ compiler strips away most of the class information when it compiles the source code. There is the Runtime Type Identification option that can be used however there is additional overhead involved with using that (see How expensive is RTTI? ) and since C++ is running native on the hardware, there is no virtual machine that is using that information to decide as to the validity of operations.

Over the years C++ has improved the ability of the programmer to write source code which allows the compiler to catch typical types of mistakes. The changes in the cast operators and the addition of several types of cast operators was one of those improvements to address an area where it is easy to make a mistake that can cause problems yet be difficult to debug.

For further details concerning the different types of C++ casts see the following:

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast and static_cast in C++

Why use static_cast<int>(x) instead of (int)x?

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106