Type safety is a fundamental concept in C++ that helps prevent errors related to incorrect use of data types. It ensures that operations are performed only on compatible types, reducing the risk of runtime errors and improving code reliability.
#include <iostream>
#include <string>
int main() {
int x = 5;
std::string s = "Hello";
// Uncommenting the next line will cause a compile-time error
// x = s; // Error: cannot assign std::string to int
std::cout << "x = " << x << std::endl;
std::cout << "s = " << s << std::endl;
return 0;
}
x
and a string s
s
to x
would result in a compile-time error due to type mismatch#include <iostream>
void printNumber(int num) {
std::cout << "The number is: " << num << std::endl;
}
int main() {
printNumber(42); // OK
// Uncommenting the next line will cause a compile-time error
// printNumber("42"); // Error: cannot convert const char* to int
return 0;
}
printNumber
that expects an integer argumentprintNumber
with an integer works as expectedprintNumber
with a string literal would result in a compile-time error#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<int> numbers;
numbers.push_back(42); // OK
numbers.push_back(10); // OK
// Uncommenting the next line will cause a compile-time error
// numbers.push_back("42"); // Error: cannot convert const char* to int
std::cout << "Numbers in the vector:" << std::endl;
for (int num : numbers) {
std::cout << num << std::endl;
}
return 0;
}
std::vector
of integers#include <iostream>
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
public:
void derivedFunction() {
std::cout << "Function from Derived class" << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
// Safe downcasting using dynamic_cast
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
derivedPtr->derivedFunction();
} else {
std::cout << "Cast failed: not a Derived object" << std::endl;
}
delete basePtr;
return 0;
}
Base
and a derived class Derived
dynamic_cast
to safely downcast from Base*
to Derived*
derivedFunction()
basePtr
doesn't actually point to a Derived
object), dynamic_cast
returns nullptr
Type safety in C++ is a crucial feature that helps prevent many common programming errors. Through strong typing, static type checking, type-safe containers, and safe casting mechanisms, C++ provides tools to write more robust and reliable code. While C++ also offers ways to bypass type safety when necessary (e.g., through C-style casts or reinterpret_cast
), adhering to type-safe practices is generally recommended for maintaining code integrity and preventing runtime errors.