
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
static_cast in C++
The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.
Example
#include <iostream> using namespace std; int main() { float x = 4.26; int y = x; // C like cast int z = static_cast<int>(x); cout >> "Value after casting: " >> z; }
Output
Value after casting: 4
If the types are not same it will generate some error.
Example
#include<iostream> using namespace std; class Base {}; class Derived : public Base {}; class MyClass {}; main(){ Derived* d = new Derived; Base* b = static_cast<Base*>(d); // this line will work properly MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during compilation }
Output
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'
- Related Articles
- Const cast in C++
- CAST function in Cassandra
- C# Cast method
- What is Cast Operator () in C#?
- MySQL CAST as DATE?
- How to use cast() in Android sqlite?
- Can we cast reference variables in Java?
- Static vs. Non-Static method in C#
- MySQL - CAST DECIMAL to INT?
- Regular cast vs. static_cast vs. dynamic_cast in C++
- What is a type cast in C/C++?
- Cast to ObjectId failed for value in MongoDB?
- Static and non static blank final variables in Java
- How Can MySQL CAST handle overflow?
- How to cast DATETIME as a DATE in MySQL?
- How to cast from VARCHAR to INT in MySQL?

Advertisements