Correct option is A
C++ supports
both static and dynamic type checking, making it a
statically typed language with
runtime type identification (RTTI) capabilities.
·
Static Type Checking:
· Performed at
compile time.
· Prevents type mismatches before program execution.
· Example:
int x = "Hello"; // Error: Type mismatch detected at compile-time
·
Dynamic Type Checking:
· Done at
runtime using
RTTI (Run-Time Type Identification).
· Allows checking object types dynamically.
· Example using dynamic_cast:
class Base { virtual void func() {} };
class Derived : public Base {};
Base* b = new Derived();
Derived* d = dynamic_cast<Derived*>(b); // Runtime type checking
· If b is
not pointing to an object of Derived, dynamic_cast returns nullptr, indicating failure.
Thus,
option (a) is correct since C++ allows
both static and dynamic type checking.
Important Key Points:
1.
Static Type Checking in C++:
· Ensures type safety
at compile-time.
· Helps prevent errors like
assigning a string to an integer variable.
2.
Dynamic Type Checking in C++:
· Uses
RTTI (Run-Time Type Identification) for checking types at runtime.
· Features like dynamic_cast, typeid, and std::any enable
runtime type checking.
3.
Use of typeid for Type Checking:
#include <iostream>
#include <typeinfo>
int main() {
int x = 5;
std::cout << "Type of x: " << typeid(x).name(); // Output: int
}
· typeid() is used to check variable types at runtime.
4.
Combination of Static and Dynamic Checking:
· Compile-time safety with static checking.
· Flexibility at runtime with dynamic checking.
Knowledge Booster:
·
Member functions are allowed to be const. Yes, but this is related to
immutability, not
type checking. Member functions can be const, but this
does not relate to type checking.
· Example of a const function:
class Example {
public:
void display() const { cout << "Constant function"; }
};
·
C++ supports dynamic checking. Yes, but it also supports
static checking, making option (a) more appropriate. Dynamic checking is
allowed, but C++ also supports
static checking. The statement does not fully describe C++'s type-checking system.