G
G
Gad_h2016-03-15 14:32:17
Programming
Gad_h, 2016-03-15 14:32:17

How does static cast work?

What happens if you use static_cast in C++ not with standard non-polymorphic classes, standard in the sense of int, double, etc. ? That is, using classes of different classes with their own blackjacks and functions.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MiiNiPaa, 2016-03-15
@MiiNiPaa

Attempts to perform a conversion using the specified conversion operators and constructors. If there is no such conversion, it will throw an error.
With pointers to classes related by inheritance, everything is somewhat more complicated:
1) Converting a pointer to a child class into a pointer to a base class.
static_cast casts types safely: the return value is a pointer to the underlying subobject of the child class.
2) Converting a pointer to a base class into a pointer to a child.
The conversion is always successful (no compilation error). If the base pointer points to a subobject of the child class, the cast succeeds and is safe. If the base pointer does not pointto a subobject of the child class, then the result of the cast is undefined and anything can happen.

struct base 
{};
struct derived: base
{};
//...
derived* d = new derived;

//Работает, безопасно
base* b = static_cast<base*>(d);

//Работает, безопасно так как b на самом деле указывает на derived
d = static_cast<derived*>(b);

b = new base;
//Undefined Behavior. Программа превращается в тыкву.
d = static_cast<derived*>(b);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question