0
0
C++programming~20 mins

Type casting in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Casting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of static_cast with integer to float
What is the output of this C++ code snippet?
C++
int main() {
    int a = 5;
    float b = static_cast<float>(a) / 2;
    std::cout << b << std::endl;
    return 0;
}
A2.0
B2
CCompilation error
D2.5
Attempts:
2 left
💡 Hint
Remember that static_cast changes the type before division.
Predict Output
intermediate
2:00remaining
Output of reinterpret_cast on pointer
What will this C++ code print?
C++
#include <iostream>
int main() {
    int x = 65;
    char* p = reinterpret_cast<char*>(&x);
    std::cout << *p << std::endl;
    return 0;
}
AUndefined behavior
BA
CCompilation error
D65
Attempts:
2 left
💡 Hint
Think about how integers are stored in memory and how char* reads bytes.
Predict Output
advanced
2:00remaining
Output of const_cast removing constness
What is the output of this code?
C++
#include <iostream>
int main() {
    const int a = 10;
    int* p = const_cast<int*>(&a);
    *p = 20;
    std::cout << a << std::endl;
    return 0;
}
AUndefined behavior
B20
CCompilation error
D10
Attempts:
2 left
💡 Hint
Modifying a const variable via const_cast is risky.
Predict Output
advanced
2:00remaining
Output of dynamic_cast with polymorphism
What will this code print?
C++
#include <iostream>
class Base { public: virtual ~Base() {} };
class Derived : public Base {};
int main() {
    Base* b = new Base();
    Derived* d = dynamic_cast<Derived*>(b);
    if (d) std::cout << "Derived" << std::endl;
    else std::cout << "Null" << std::endl;
    delete b;
    return 0;
}
ANull
BRuntime error
CCompilation error
DDerived
Attempts:
2 left
💡 Hint
dynamic_cast returns nullptr if cast fails.
🧠 Conceptual
expert
2:00remaining
Which cast is safest for downcasting polymorphic types?
In C++, when you want to safely convert a base class pointer to a derived class pointer, which cast should you use?
Astatic_cast
Breinterpret_cast
Cdynamic_cast
Dconst_cast
Attempts:
2 left
💡 Hint
Consider runtime type checking.