My teacher included the lines below in one of our examples of casting. c
is an object of class Circle
which inherits from class Point
. In my search for an answer to the question "Can I cast an object of class Point
to type Circle
?" I found that he uses a different syntax than every website I've been on. The websites all use static_cast
and dynamic_cast
syntax. He won't be using static_cast and dynamic_cast on the test and I'm just wondering what he is using and how that operates.
Also, if you have an answer to whether I can cast a base object to a derived type, I thank you immensely.
output << "the center of the circle is at " << (Point) c;
// casting `Circle` object `c` with type `(Point)`, calls the first overloaded >stream insertion operator"
(Point)c
is known as a "C-style" cast. This can basically be thought of as a brute force cast that does whatever it can to make the cast succeed. This means it could end up causing a static_cast
a const_cast
or even a reinterpret_cast
.
When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order:
Source: https://en.cppreference.com/w/cpp/language/explicit_cast
And from Stroustrup himself:
Explicit type conversions (often called casts to remind you that they are used to prop up something broken) are best avoided.
and
C-style casts should have been deprecated in favor of named casts.
Stroustrup, Bjarne. A Tour of C++ (C++ In-Depth Series) (Kindle Location 7134). Pearson Education. Kindle Edition.
So the named casts are recommended. In practice I still encounter professional code using C-style casts simply because it makes code more succinct and readable and is -- if you know what you're doing -- normally equivalent to static_cast
in the places its used. For what its worth I think C-style casts are okay if used for these reasons in a context that makes it obvious that it will result in a static_cast
, and Stroustrup is coming from an overly object-oriented perspective in his general disdain for casting. But you should prefer the named casts.
Your teacher is probably using the C-style cast as a less scary-looking introduction to casting.