0% found this document useful (0 votes)
7 views

Type Conversion in C++ - Google Docs

Type conversion in C++ involves converting a variable from one data type to another, primarily through automatic type conversion and type casting. Automatic conversion occurs when the compiler promotes smaller data types to larger ones to avoid data loss, while type casting allows programmers to explicitly convert types as needed. C++ provides specific casting operators such as static_cast, const_cast, dynamic_cast, and reinterpret_cast for various conversion scenarios.

Uploaded by

Sukhwinder Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Type Conversion in C++ - Google Docs

Type conversion in C++ involves converting a variable from one data type to another, primarily through automatic type conversion and type casting. Automatic conversion occurs when the compiler promotes smaller data types to larger ones to avoid data loss, while type casting allows programmers to explicitly convert types as needed. C++ provides specific casting operators such as static_cast, const_cast, dynamic_cast, and reinterpret_cast for various conversion scenarios.

Uploaded by

Sukhwinder Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

‭ ype Conversion in C++‬

T
‭Type conversion refers to converting a variable from one data type to another. This is‬
‭commonly used when we need to perform operations on variables of different types or‬
‭ensure compatibility between data types.‬
‭It is of two types:-‬
‭1.‬ ‭Automatic Type Conversion‬
‭2.‬ ‭Type casting‬
‭ . Automatic Type Conversion (Implicit Conversion):-‬‭Automatic type conversion, also‬
1
‭known as‬‭implicit conversion‬‭or‬‭type promotion‬‭, is a process where the compiler‬
‭automatically converts a variable or expression from one data type to another. This happens‬
‭when:‬
‭1.‬ ‭Data types are compatible‬‭, and‬
‭2.‬ ‭The destination type is larger or more precise than the source type‬‭.‬
‭The main goal of automatic type conversion is to avoid data loss and ensure compatibility‬
‭during operations involving mixed data types.‬
‭Rules of Automatic Type Conversion‬
‭1.‬ ‭Promotion to Larger Data Types‬‭: Smaller data types (e.g.,‬‭ int‬
‭,‬‭char‬ ‭) are‬
float‬
‭automatically promoted to larger data types (e.g.,‬‭ double‬
‭,‬‭ ‭) to avoid precision‬
‭loss.‬
‭2. Order of Promotion‬‭: C++ follows a hierarchy of data types for promotion:‬

‭ ool → char → short → int → unsigned int → long → float → double → long double‬
b
‭3. Happens Automatically‬‭: The programmer does not need to write explicit code for the‬
‭conversion.‬
‭Examples of Automatic Type Conversion‬
‭1. Integer to Float Conversion‬
‭ include <iostream>‬
#
‭using namespace std;‬

‭int main() {‬
‭int a = 10;‬
‭float b = a; // 'a' is automatically converted to float‬
‭cout << "Value of b: " << b << endl; // Output: 10.0‬
‭return 0;‬
‭}‬
‭Advantages of Automatic Type Conversion‬
‭1.‬ ‭Convenience‬‭: Reduces the need for explicit type casting by the programmer.‬
‭2.‬ ‭Avoids Errors‬‭: Ensures compatibility in expressions by promoting smaller types to‬
‭larger types.‬
‭3.‬ ‭Improves Readability‬‭: Simplifies code when dealing with mixed-type operations.‬
‭Limitations of Automatic Type Conversion‬
‭1.‬ ‭Data Loss in Some Cases‬‭:-When converting a large integer to a floating-point type‬
‭with insufficient precision.‬
‭int largeValue = 123456789;‬
‭float converted = largeValue; // Precision may be lost‬
‭2.‬ ‭Unintended Behavior‬‭:-In mixed operations, unintended results may occur if the‬
‭programmer does not account for promotions.‬
‭unsigned int a = 10;‬
‭int b = -20;‬
‭cout << a + b; // May result in unexpected behavior due to unsigned conversion‬
‭3.‬ ‭Type Promotion Order‬‭:-Can lead to unexpected promotions in complex expressions.‬
‭2. Type Casting:-‬‭Type casting is the process of converting a variable or expression from‬
‭one data type to another. It can be done by the user as per the requirements.‬
‭In C++, this can be done in two ways:‬
‭1.‬ ‭Implicit Type Casting‬‭(also called type promotion, handled automatically by the‬
‭compiler).‬
‭2.‬ ‭Explicit Type Casting‬‭(manually specified by the programmer).‬
‭Type Casting in C++‬
‭Type casting is the process of converting a variable or expression from one data type to‬
‭another. In C++, this can be done in two ways:‬
‭1.‬ ‭Implicit Type Casting‬‭(also called type promotion, handled automatically by the‬
‭compiler).‬
‭2.‬ ‭Explicit Type Casting‬‭(manually specified by the programmer).‬
‭1. Implicit Type Casting‬‭Performed automatically by the compiler.Converts smaller data‬
‭types to larger or more compatible types.Examples include converting an‬‭ int‬‭to a‬‭
float‬‭or‬
char‬‭to an‬‭
‭a‬‭ int‬ ‭.‬
‭Example of Implicit Type Casting‬
‭ include <iostream>‬
#
‭using namespace std;‬
‭int main() {‬
‭int a = 10;‬
‭float b = a; // Implicit conversion from int to float‬
‭cout << "Value of b: " << b << endl; // Output: 10.0‬
‭return 0;‬
‭}‬
‭2. Explicit Type Casting‬
‭●‬ ‭Requires the programmer to specify the type to which a variable or expression should‬
‭be converted.‬
‭●‬ ‭Useful when you want to enforce a specific conversion, even if data loss might occur.‬
‭Syntax for Explicit Casting‬
‭(datatype) expression‬
‭Examples of Explicit Type Casting‬
‭Integer to Float:‬
‭ include <iostream>‬
#
‭using namespace std;‬
‭int main() {‬
‭int a = 5;‬
‭float b = (float)a; // Explicit casting from int to float‬
‭cout << "Value of b: " << b << endl; // Output: 5.0‬
‭return 0;‬
‭}‬
‭Advantages of Explicit Type Casting‬
‭1.‬ ‭Precision Control‬‭: Helps manage the exact representation of data types.‬
‭2.‬ ‭Avoids Ambiguity‬‭: Makes the programmer's intent clear.‬
‭3.‬ ‭Overrules Compiler Behavior‬‭: Allows conversions that the compiler would otherwise‬
‭restrict.‬
‭Disadvantages:-‬
‭1.‬ ‭Undefined Behavior‬‭: Using‬‭ reinterpret_cast‬‭carelessly can lead to‬
‭unpredictable results.‬
‭2.‬ ‭Complex Code‬‭: Overuse of explicit casting can reduce code readability.‬
‭Type Casting in C++: Specialized Casts‬
‭C++ provides four specific type casting operators to handle different type conversion‬
‭scenarios. These are more explicit and safer than traditional C-style casting. Each cast‬
‭serves a distinct purpose and is used in appropriate contexts.‬
‭1.‬‭ static_cast‬
‭●‬ ‭Used for‬‭well-defined conversions‬‭between types.‬
‭●‬ ‭Performs compile-time checks but cannot cast between unrelated types.‬
‭●‬ ‭Commonly used for:‬
‭○‬ ‭Converting between numeric types.‬
‭○‬ ‭Upcasting or downcasting in class hierarchies (without polymorphism).‬
‭○‬ ‭Explicit conversions between compatible types.‬
‭Syntax:-‬‭static_cast<new_type>(expression)‬
‭Example:‬
‭ include <iostream>‬
#
‭using namespace std;‬
‭int main() {‬
‭float x = 3.14;‬
‭int y = static_cast<int>(x); // Converts float to int‬
‭cout << "Value of y: " << y << endl; // Output: 3‬
‭return 0;‬
‭}‬

‭Use in Class Hierarchies:‬


c‭ lass Base {};‬
‭class Derived : public Base {};‬
‭Base* b = new Derived();‬
‭Derived* d = static_cast<Derived*>(b); // Safe because Base and Derived are related‬
const_cast‬
‭2.‬‭
‭●‬ ‭Used to‬‭add or remove the‬‭ const‬‭qualifier‬‭from a variable.‬
‭●‬ ‭Can be applied to pointers or references but does not modify the actual constness of‬
‭the object.‬
‭●‬ ‭Commonly used to:‬
const‬‭objects in legacy APIs.‬
‭○‬ ‭Temporarily modify‬‭
const‬‭objects to functions expecting non-const‬
‭○‬ ‭Avoid warnings when passing‬‭
‭arguments.‬
‭Syntax:-‬‭const_cast<new_type>(expression)‬
‭Example:‬
‭ include <iostream>‬
#
‭using namespace std;‬
‭void modifyValue(int* ptr) {‬
‭*ptr = 42;‬
‭}‬
‭int main() {‬
‭const int x = 10;‬
‭int* ptr = const_cast<int*>(&x); // Remove constness‬
‭modifyValue(ptr);‬
‭cout << "Value of x: " << x << endl; // Output: Undefined behavior (modifies a const‬
‭object)‬
‭return 0;‬
‭}‬
‭3.‬‭ dynamic_cast‬
‭●‬ ‭Used for‬‭safe casting‬‭in polymorphic class hierarchies (i.e., classes with at least one‬
virtual‬‭function).‬

‭●‬ ‭Performs‬‭runtime type checking‬‭and ensures the cast is valid.‬
‭●‬ ‭Returns:‬
‭○‬ ‭The pointer to the derived class if successful.‬
‭○‬ ‭ nullptr‬‭for invalid casts when used with pointers.‬
‭○‬ ‭Throws‬‭ std::bad_cast‬‭exception for invalid casts when used with‬
‭references.‬
‭Syntax:-‬‭dynamic_cast<new_type>(expression)‬
‭Example:‬
‭ include <iostream>‬
#
‭using namespace std;‬
c‭ lass Base {‬
‭public:‬
‭virtual void show() {}‬
‭};‬
‭class Derived : public Base {‬
‭public:‬
‭void display() { cout << "Derived class" << endl; }‬
‭};‬
‭int main() {‬
‭Base* b = new Derived();‬
‭// Safe downcasting‬
‭Derived* d = dynamic_cast<Derived*>(b);‬
‭if (d) {‬
‭d->display(); // Output: Derived class‬
‭} else {‬
‭cout << "Invalid cast" << endl;‬
‭}‬
‭return 0;‬
‭}‬
‭4.‬‭ reinterpret_cast‬
‭●‬ ‭Used for‬‭low-level, unsafe casting‬‭between unrelated types (e.g., pointers to‬
‭unrelated objects or integers).‬
‭●‬ ‭Does not perform any runtime checks.‬
‭●‬ ‭Commonly used in scenarios like:‬
‭○‬ ‭Converting pointers to integers and vice versa.‬
‭○‬ ‭Interpreting raw binary data.‬
‭Syntax:-‬‭reinterpret_cast<new_type>(expression)‬
‭Example:‬
‭ include <iostream>‬
#
‭using namespace std;‬
‭int main() {‬
‭int a = 42;‬
‭int* ptr = &a;‬
‭uintptr_t address = reinterpret_cast<uintptr_t>(ptr);‬
‭cout << "Address as integer: " << address << endl;‬
‭int* newPtr = reinterpret_cast<int*>(address);‬
‭cout << "Value pointed by newPtr: " << *newPtr << endl; // Output: 42‬
‭return 0;‬
‭}‬

You might also like