type_safety


Concept: type safety

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.

Key Characteristics

Example 1: Strong Typing

#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;
}

Explanation

Example 2: Static Type Checking

#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;
}

Explanation

Example 3: Type-Safe Containers

#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;
}

Explanation

Example 4: Type-Safe Casting

#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;
}

Explanation

Summary

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.

Previous Page | Course Schedule | Course Content