C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Type Conversion Function: Convert Current Type Class To Another Type in C++

In this tutorial, we will learn about type conversion functions in C++. Type conversion functions, also known as conversion operators, are special member functions that allow a class object to be implicitly converted to another type. This can be useful when you want to provide a way to convert your user-defined type to a built-in or another user-defined type.

  • Basic usage of type conversion functions:

Here's a simple example demonstrating the use of a type conversion function:

#include <iostream>

class Fraction {
private:
    int numerator;
    int denominator;

public:
    Fraction(int num, int den) : numerator(num), denominator(den) {}

    // Type conversion function for converting Fraction to double
    operator double() const {
        return static_cast<double>(numerator) / denominator;
    }
};

int main() {
    Fraction frac(3, 4);
    double result = frac; // Implicitly converts Fraction to double using the type conversion function

    std::cout << "Fraction as double: " << result << std::endl; // Output: Fraction as double: 0.75
    return 0;
}

In this example, we define a Fraction class with a type conversion function operator double(). The conversion function allows objects of the Fraction class to be implicitly converted to double. In the main() function, we create a Fraction object and implicitly convert it to a double using the type conversion function.

  • Type conversion function with explicit keyword:

By default, type conversion functions are implicitly applied, which can sometimes lead to unexpected results. You can use the explicit keyword before the conversion function to prevent implicit conversions:

#include <iostream>

class Fraction {
private:
    int numerator;
    int denominator;

public:
    Fraction(int num, int den) : numerator(num), denominator(den) {}

    // Type conversion function with explicit keyword
    explicit operator double() const {
        return static_cast<double>(numerator) / denominator;
    }
};

int main() {
    Fraction frac(3, 4);

    // This will result in a compilation error, as the conversion is not allowed implicitly
    // double result = frac;

    // Use static_cast to explicitly convert Fraction to double
    double result = static_cast<double>(frac);
    std::cout << "Fraction as double: " << result << std::endl; // Output: Fraction as double: 0.75

    return 0;
}

In this example, we add the explicit keyword before the type conversion function operator double(). This prevents the implicit conversion of a Fraction object to a double. Instead, we need to use static_cast to explicitly convert the Fraction object to a double.

That's it for our C++ type conversion function tutorial. Understanding type conversion functions is crucial for writing clean and efficient code, especially when working with user-defined types that need to interact with other data types. It allows you to define how your objects should be converted to other types in a clean and consistent manner.

  1. How to create type conversion functions in C++:

    #include <iostream>
    
    class Temperature {
    private:
        double celsius;
    
    public:
        Temperature(double celsius) : celsius(celsius) {}
    
        // Type conversion function
        operator double() const {
            return celsius;
        }
    };
    
    int main() {
        Temperature temp(25.0);
        double value = temp; // Implicit conversion using the type conversion function
        std::cout << "Temperature in Celsius: " << value << std::endl;
    
        return 0;
    }
    
  2. Overloading type conversion operators in C++:

    #include <iostream>
    
    class Distance {
    private:
        double meters;
    
    public:
        Distance(double meters) : meters(meters) {}
    
        // Conversion operator for int
        operator int() const {
            return static_cast<int>(meters);
        }
    
        // Conversion operator for double
        operator double() const {
            return meters;
        }
    };
    
    int main() {
        Distance d(100.5);
        int intValue = d;    // Implicit conversion to int
        double doubleValue = d; // Implicit conversion to double
    
        std::cout << "Distance as int: " << intValue << std::endl;
        std::cout << "Distance as double: " << doubleValue << std::endl;
    
        return 0;
    }
    
  3. Converting between user-defined types in C++:

    #include <iostream>
    
    class Fahrenheit {
    private:
        double value;
    
    public:
        Fahrenheit(double value) : value(value) {}
    
        // Conversion operator to Celsius
        operator double() const {
            return (value - 32.0) * 5.0 / 9.0;
        }
    };
    
    class Celsius {
    private:
        double value;
    
    public:
        Celsius(double value) : value(value) {}
    
        // Conversion operator to Fahrenheit
        operator Fahrenheit() const {
            return Fahrenheit(value * 9.0 / 5.0 + 32.0);
        }
    };
    
    int main() {
        Celsius celsiusValue(25.0);
        Fahrenheit fahrenheitValue = celsiusValue; // Implicit conversion to Fahrenheit
    
        std::cout << "Temperature in Fahrenheit: " << fahrenheitValue << std::endl;
    
        return 0;
    }
    
  4. Type conversion functions and operator overloading in C++:

    #include <iostream>
    
    class Complex {
    private:
        double real;
        double imag;
    
    public:
        Complex(double real, double imag) : real(real), imag(imag) {}
    
        // Conversion operator to double (magnitude)
        operator double() const {
            return sqrt(real * real + imag * imag);
        }
    
        // Operator overloading for addition
        Complex operator+(const Complex& other) const {
            return Complex(real + other.real, imag + other.imag);
        }
    };
    
    int main() {
        Complex c1(3.0, 4.0);
        Complex c2(1.0, 2.0);
    
        double magnitude = c1; // Implicit conversion to double
        Complex sum = c1 + c2; // Operator overloading
    
        std::cout << "Magnitude of c1: " << magnitude << std::endl;
        std::cout << "Sum of c1 and c2: " << sum.real << " + " << sum.imag << "i" << std::endl;
    
        return 0;
    }