C++ Type Casting

c_style.c
C
#include <stdio.h>
int main() {
int num = 5;
double converted_num = (double)num; // Cast occurs here
printf("%f", converted_num);
return 0;
}
c_style.cpp
C++
#include <iostream>
int main() {
int num = 5;
double converted_num = (double)num; // No difference!
std::cout << converted_num << "\n";
return 0;
}
static_cast.cpp
C++
#include <iostream>
int main() {
int x = 13;
auto y = static_cast<double>(x);
std::cout << "Value of y: " << y << "\n";
return 0;
}
failed_static_cast.cpp
C++
#include <string>
int main() {
int x = 13;
// This does not compile because an integer cannot be cast to a string
auto y = static_cast<std::string>(x);
return 0;
}
dynamic_cast.cpp
C++
#include <iostream>
class Base {
public:
virtual void check() {
std::cout << "This object is of type Base\n";
}
};
class Derived : public Base {
public:
void check() override {
std::cout << "This object is of type Derived\n";
}
};
int main() {
Derived derived;
Base* base = &derived;
auto* new_derived = dynamic_cast<Derived*>(base);
// Always check if downcast was successful to prevent segfaults
if (new_derived == nullptr) {
std::cerr << "Downcast failed.\n";
return 1;
} else {
new_derived->check();
}
return 0;
}
const_cast.cpp
C++
void legacy_print(char* str);
void modern_func(const std::string& message) {
legacy_print(const_cast<char*>(message.c_str()));
}
int main() {
const std::string message = "Test";
modern_func();
return 0;
}
reinterpret_cast.cpp
C++
class Object {
private:
uint32_t data;
float more_data;
std::string message;
};
int main() {
Object object;
auto* bytes = reinterpret_cast<uint8_t*>(&object);
for (auto i = 0; i < sizeof(Object); ++i) {
printf("%02X ", bytes[i]);
}
return 0;
}
bit_cast.cpp
C++
#include <bit>
#include <cstdint>
#include <iostream>
constexpr double fp = 1337.67;
constexpr auto u64 = std::bit_cast<uint64_t>(fp);
int main() {
std::cout << "Original floating point value: " << fp
<< "\nConverted to an integer representation: " << u64
<< std::endl;
return 0;
}
Original floating point value: 1337.67
Converted to an integer representation: 4653597950322860360
  1. https://en.cppreference.com/cpp/language/explicit_cast ↩︎
  2. https://en.cppreference.com/w/cpp/numeric/bit_cast.html ↩︎

Discover more from shared_ptr

Subscribe now to keep reading and get access to the full archive.

Continue reading