Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
static_cast in C++
Next article icon

static_cast in C++

Last Updated : 11 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Cast operator is a unary operator which forces one data type to be converted into another data type.

C++ supports 4 types of casting:

  1. Static Cast
  2. Dynamic Cast
  3. Const Cast
  4. Reinterpret Cast

This article focuses on discussing the static_cast in detail.

Static Cast

This is the simplest type of cast that can be used. It is a compile-time cast. It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions.

Syntax of static_cast

static_cast <dest_type> (source);

The return value of static_cast will be of dest_type.

The static_cast operator is essential for safe type conversion in C++.

Example of static_cast

Below is the C++ program to implement static_cast:

C++
// C++ Program to demonstrate // static_cast #include <iostream> using namespace std;  // Driver code int main() {     float f = 3.5;      // Implicit type case     // float to int     int a = f;     cout << "The Value of a: " << a;      // using static_cast for float to int     int b = static_cast<int>(f);     cout << "\nThe Value of b: " << b; } 

Output
The Value of a: 3 The Value of b: 3

The behavior of static_cast for Different Scenarios

1. static_cast for primitive data type pointers:

Now let’s make a few changes to the above code.

C++
// C++ Program to demonstrate  // static_cast char* to int* #include <iostream> using namespace std;  // Driver code int main() {   int a = 10;   char c = 'a';      // Pass at compile time,    // may fail at run time   int* q = (int*)&c;   int* p = static_cast<int*>(&c);   return 0; } 


Output

error: invalid static_cast from type 'char*' to type 'int*'

Explanation: This means that even if you think you can somehow typecast a particular object pointer into another but it's illegal, the static_cast will not allow you to do this.

2. Converting an Object using a User-Defined Conversion Operator

static_cast is able to call the conversion operator of the class if it is defined. Let's take another example of converting an object to and from a class.

Example:

C++
// C++ Program to cast // class object to string // object #include <iostream> #include <string> using namespace std;  // new class class integer {     int x;  public:     // constructor     integer(int x_in = 0)         : x{ x_in }     {         cout << "Constructor Called" << endl;     }      // user defined conversion operator to string type     operator string()     {         cout << "Conversion Operator Called" << endl;         return to_string(x);     } };  // Driver code int main() {     integer obj(3);     string str = obj;     obj = 20;      // using static_cast for typecasting     string str2 = static_cast<string>(obj);     obj = static_cast<integer>(30);      return 0; } 

Output
Constructor Called Conversion Operator Called Constructor Called Conversion Operator Called Constructor Called

Explanation: Lets the try to understand the above output line by line:

  1. When obj is created then the constructor is called which in our case is also a Conversion Constructor (for C++14 rules are changed a bit).
  2. When you create str out of obj, the compiler will not throw an error as we have defined the Conversion operator.
  3. When you make obj = 20, you are actually calling the conversion constructor.
  4. When you make str2 out of static_cast, it is pretty similar to string str = obj; but with tight type checking.
  5. When you write obj = static_cast <integer> (30), you convert 30 into an integer using static_cast.

3. static_cast for Inheritance in C++

static_cast can provide both upcasting and downcasting in case of inheritance. The following example demonstrates the use of static_cast in the case of upcasting.

Example:

C++
// C++ Program to demonstrate  // static_cast in inheritance #include <iostream> using namespace std; class Base  {}; class Derived : public Base  {};  // Driver code int main() {   Derived d1;      // Implicit cast allowed   Base* b1 = (Base*)(&d1);      // upcasting using static_cast   Base* b2 = static_cast<Base*>(&d1);   return 0; } 


Explanation: The above code will compile without any error.

  1. We took the address of d1 and explicitly cast it into Base and stored it in b1.
  2. We took the address of d1 and used static_cast to cast it into Base and stored it in b2.

In the above example, we inherited the base class as public. What happens when we inherit it as private? The below example demonstrate the following:

Example:

C++
// C++ program to demonstrate  // static_cast in case of  // private inheritance #include <iostream> using namespace std;  class Base  {};  class Derived: private Base  {    // Inherited private/protected    // not public };  // Driver code int main() {       Derived d1;      // Implicit type cast allowed   Base* b1 = (Base*)(&d1);      // static_cast not allowed   Base* b2 = static_cast<Base*>(&d1);   return 0; } 


Compile-time Error:

[Error] 'Base' is an inaccessible base of 'Derived'

Explanation: The above code will not compile even if you inherit it as protected.

So to use static_cast in case of inheritance, the base class must be accessible, non virtual and unambiguous.

4. static_cast to Cast 'to and from' Void Pointer

static_cast operator allows casting from any pointer type to void pointer and vice versa.

Example:

C++
// C++ program to demonstrate  // static_cast to cast 'to and  // from' the void pointer #include <iostream> using namespace std;  // Driver code int main() {   int i = 10;   void* v = static_cast<void*>(&i);   int* ip = static_cast<int*>(v);   cout << *ip;   return 0; } 

Output
10

Next Article
static_cast in C++

A

amanrk92
Improve
Article Tags :
  • C++
Practice Tags :
  • CPP

Similar Reads

    Dynamic _Cast in C++
    In C++, dynamic_cast is a cast operator that converts data from one type to another type at runtime. It is mainly used in inherited class hierarchies for safely casting the base class pointer or reference to derived class (called downcasting). To work with dynamic_cast, there must be one virtual fun
    5 min read
    C++ Static Data Members
    Static data members are class members that are declared using static keywords. A static member has certain special characteristics which are as follows:Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
    5 min read
    Static Member Function in C++
    The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with t
    4 min read
    std::any Class in C++
    any is one of the newest features of C++17 that provides a type-safe container to store single value of any type. In layman's terms, it is a container which allows one to store any value in it without worrying about the type safety. It acts as an extension to C++ by mimicking behaviour similar to an
    6 min read
    Casting Operators in C++
    The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences