C++ Typecasting (794255)

Файл №794255 C++ Typecasting (C++ Typecasting)C++ Typecasting (794255)2019-05-08СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла

C++ TypecastingTypecasting is the concept of converting the value of one type into another type. For example, you mighthave a float that you need to use in a function that requires an integer.Implicit conversionAlmost every compiler makes use of what is called automatic typecasting. It automatically converts one typeinto another type. If the compiler converts a type it will normally give a warning. For example this warning:conversion from „double‟ to „int‟, possible loss of data.The problem with this is, that you get a warning (normally you want to compile without warnings and errors)and you are not in control. With control we mean, you did not decide to convert to another type, thecompiler did.

Also the possible loss of data could be unwanted.Explicit conversionThe C and C++ languages have ways to give you back control. This can be done with what is called anexplicit conversion. Sure you may still lose data, but you decide when to convert to another type and youdon‟t get any compiler warnings.Let‟s take a look at an example that uses implicit and explicit conversion:#include <iostream>using namespace std;int main() {int a;double b=2.55;a = b;cout << a << endl;a = (int)b;cout << a << endl;a = int(b);cout << a << endl;}Note: the output of all cout statements is 2.The first conversion is an implicit conversion (the compiler decides.) As explained before, the compilershould give a warning.The second conversion is an explicit typecast, in this case the C style explicit typecast.The third conversion is also explicit typecast, in this case the C++ style explicit typecast.Four typecast operatorsThe C++ language has four typecast operators:static_castreinterpret_castconst_castdynamic_castStatic_castAutomatic conversions are common in every C++ program.

You have:Standard conversion. For instance: from short to int or from int to float.User defined conversions (Class conversions.)Conversion from derived class to base class.The static_cast can be used for all these types of conversion. Take a look at an example:int a = 5;int b = 2;double out;// typecast a to doubleout = static_cast<double>(a)/b;It may take some time to get used to the notation of the typecast statement.

(The rumour goes that BjarneStroustrup made it difficult on purpose, to discourage the use of typecasting.) Between the angle bracketsyou place to which type the object should be casted. Between the parentheses you place the object that iscasted.It is not possible to use static_cast on const objects to non-const objects. For this you have to useconst_cast. (Further down we take a look at const_cast.)If an automatic conversion is valid (from enum to int for instance) then you can use static_cast to do theopposite (from int to enum.)For instance:enum my_numbers { a=10, c=100, e=1000 };const my_numbers b = static_cast<my_numbers> (50);const my_numbers d = static_cast<my_numbers> (500);Note: We add some new values (b and d).

These are type-cast from int to enum.Reinterpret_castThe reinterpret_cast is used for casts that are not safe:Between integers and pointersBetween pointers and pointersBetween function-pointers and function-pointersFor instance the typecast from an integer to a character pointer:char *ptr_my = reinterpret_cast<char *>(0xb0000);Note: the example above uses a fixed memory location.If we use the reinterpret_cast on a null-pointer then we get a null-pointer of the asked type:char *ptr_my = 0;int *ptr_my_second = reinterpret_cast<int *>(ptr_my);The reinterpret_cast is almost as dangerous as an “old fashion” cast. The only guaranty that you get is thatif you cast an object back to the original data-type (before the first cast) then the original value is alsorestored (of course only if the data-type was big enough to hold the value.)The only difference with an old fashion cast is that const is respected.

This means that a reinterpret_cast cannot be used to cast a const object to non-const object. For instance:char *const MY = 0;// This is not valid because MY is a const!!int *ptr_my = reinterpret_cast<int *>( MY);Const_castThe only way to cast away the const properties of an object is to use const_cast. Take a look at an example:void a(Person* b);int main() {const Person *ptr_my = new Person("Joe");a( const_cast<Person *>(ptr_my) );}The use of const_cast on an object doesn‟t guarantee that the object can be used (after the const is castaway.) Because it is possible that the const-objects are put in read-only memory by the program.The const_cast can not be used to cast to other data-types, as it is possible with the other cast functions.Take a look at the next example:int a;const char *ptr_my = "Hello";a = const_cast<int *>(ptr_my);a = reinterpret_cast<const char*>(ptr_my);a = reinterpret_cast<int *>(const_cast<char *>(ptr_my) );Note: casting from const char * to int * isn‟t very good (not to say a very dirty trick.) Normally you won‟t dothis.The first statement (const_cast) will give an error, because the const_cast can‟t convert the type.

Thesecond statement (reinterpret_cast) will also give an error, because the reinterpret_cast can‟t cast the constaway. The third statement will work (mind the note. It is a dirty trick, better not use it.)Runtime Type Information (RTTI)Runtime Type Information (RTTI) is the concept of determining the type of any variable during execution(runtime.) The RTTI mechanism contains:The operator dynamic_castThe operator typeidThe struct type_infoRTTI can only be used with polymorphic types. This means that with each class you make, you must have atleast one virtual function (either directly or through inheritance.)Compatibility note: On some compilers you have to enable support of RTTI to keep track of dynamic types.So to make use of dynamic_cast (see next section) you have to enable this feature.

See you compilerdocumentation for more detail.Dynamic_castThe dynamic_cast can only be used with pointers and references to objects. It makes sure that the result ofthe type conversion is valid and complete object of the requested class. This is way a dynamic_cast willalways be successful if we use it to cast a class to one of its base classes. Take a look at the example:class Base_Class { };class Derived_Class: public Base_Class { };Base_Class a; Base_Class * ptr_a;Derived_Class b; Derived_Class * ptr_b;ptr_a = dynamic_cast<Base_Class *>(&b);ptr_b = dynamic_cast<Derived_Class *>(&a);The first dynamic_cast statement will work because we cast from derived to base. The second dynamic_caststatement will produce a compilation error because base to derived conversion is not allowed withdynamic_cast unless the base class is polymorphic.If a class is polymorphic then dynamic_cast will perform a special check during execution.

This check ensuresthattheexpressionisavalidandcompleteobjectoftherequestedclass.Take a look at the example:#include <iostream>#include <exception>using namespace std;class Base_Class { virtual void dummy() {} };class Derived_Class: public Base_Class { int a; };int main () {try {Base_Class * ptr_a = new Derived_Class;Base_Class * ptr_b = new Base_Class;Derived_Class * ptr_c;ptr_c = dynamic_cast< Derived_Class *>(ptr_a);if (ptr_c ==0) cout << "Null pointer on first type-cast" << endl;ptr_c = dynamic_cast< Derived_Class *>(ptr_b);if (ptr_c ==0) cout << "Null pointer on second type-cast" << endl;} catch (exception& my_ex) {cout << "Exception: " << my_ex.what();}return 0;}In the example we perform two dynamic_casts from pointer objects of type Base_Class* (namely ptr_a andptr_b) to a pointer object of type Derived_Class*.If everything goes well then the first one should be successful and the second one will fail.

The pointers ptr_aand ptr_b are both of the type Base_Class. The pointer ptr_a points to an object of the type Derived_Class.The pointer ptr_b points to an object of the type Base_Class. So when the dynamic type cast is performedthen ptr_a is pointing to a full object of class Derived_Class, but the pointer ptr_b points to an object of classBase_Class. This object is an incomplete object of class Derived_Class; thus this cast will fail!Because this dynamic_cast fails a null pointer is returned to indicate a failure.

When a reference type isconverted with dynamic_cast and the conversion fails then there will be an exception thrown out instead ofthe null pointer. The exception will be of the type bad_cast.With dynamic_cast it is also possible to cast null pointers even between the pointers of unrelated classes.Dynamic_cast can cast pointers of any type to void pointer(void*).Typeid and typ_infoIf a class hierarchy is used then the programmer doesn‟t have to worry (in most cases) about the data-type ofa pointer or reference, because the polymorphic mechanism takes care of it. In some cases the programmerwants to know if an object of a derived class is used.

Характеристики

Тип файла
PDF-файл
Размер
416,44 Kb
Материал
Тип материала
Высшее учебное заведение

Тип файла PDF

PDF-формат наиболее широко используется для просмотра любого типа файлов на любом устройстве. В него можно сохранить документ, таблицы, презентацию, текст, чертежи, вычисления, графики и всё остальное, что можно показать на экране любого устройства. Именно его лучше всего использовать для печати.

Например, если Вам нужно распечатать чертёж из автокада, Вы сохраните чертёж на флешку, но будет ли автокад в пункте печати? А если будет, то нужная версия с нужными библиотеками? Именно для этого и нужен формат PDF - в нём точно будет показано верно вне зависимости от того, в какой программе создали PDF-файл и есть ли нужная программа для его просмотра.

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6439
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее