← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 8 of 17

C++ static_cast

What is static_cast?

The static_cast operator is used for standard, compile-time type conversions. It converts one data type to another, such as float to integer, and is checked by the compiler to ensure the conversion is safe.

Example: What is static_cast?

cpp
#include <iostream>

int main() {
	float f = 3.9f;
	int i = static_cast<int>(f);
	std::cout << i << std::endl;
	return 0;
}

Enum Conversions

You can use static_cast to convert scoped enums (enum classes) to their underlying integer values, or to convert integers back to enum values.

Example: Enum Conversions

cpp
#include <iostream>

enum class Color { Red, Green, Blue };

int main() {
	int value = static_cast<int>(Color::Green);
	std::cout << value << std::endl;
	return 0;
}

Upcasting in Inheritance

You can use static_cast to cast a derived class pointer up to a base class pointer. This type of conversion is always safe because a derived object contains all the components of its base class.

Example: Upcasting in Inheritance

cpp
#include <iostream>

class Animal {};
class Dog : public Animal {};

int main() {
	Dog d;
	Animal *a = static_cast<Animal *>(&d);
	std::cout << "Upcast succeeded" << std::endl;
	return 0;
}

Void Pointer Conversions

A void pointer (void*) is a generic pointer that has no associated data type. You can use static_cast to convert a void pointer back to its original typed pointer so you can dereference it.

Example: Void Pointer Conversions

cpp
#include <iostream>

int main() {
	int value = 42;
	void *vptr = &value;
	int *iptr = static_cast<int *>(vptr);
	std::cout << *iptr << std::endl;
	return 0;
}

static_cast vs C-style Casts

Unlike older C-style casts like (int)value, static_cast is safer because it is checked by the compiler. It prevents you from accidentally making invalid and unsafe type conversions.

Example: static_cast vs C-style Casts

cpp
#include <iostream>

int main() {
	double d = 3.9;
	int a = (int)d;
	int b = static_cast<int>(d);
	std::cout << a << " " << b << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.