Challenge - 5 Problems
Type Casting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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; }
Attempts:
2 left
💡 Hint
Remember that static_cast changes the type before division.
✗ Incorrect
Casting 'a' to float makes the division a floating-point division, so 5/2 becomes 2.5.
❓ Predict Output
intermediate2: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; }
Attempts:
2 left
💡 Hint
Think about how integers are stored in memory and how char* reads bytes.
✗ Incorrect
The integer 65 corresponds to ASCII 'A'. reinterpret_cast treats the int's address as char*, so *p reads the first byte, printing 'A'.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
Modifying a const variable via const_cast is risky.
✗ Incorrect
Changing a const variable through const_cast causes undefined behavior, so output is unpredictable.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
dynamic_cast returns nullptr if cast fails.
✗ Incorrect
Since 'b' points to Base, not Derived, dynamic_cast returns nullptr, so output is 'Null'.
🧠 Conceptual
expert2: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?
Attempts:
2 left
💡 Hint
Consider runtime type checking.
✗ Incorrect
dynamic_cast performs runtime checks and returns nullptr if the cast is invalid, making it safe for downcasting.