Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement type casting from one class to another

Tags:

c++

oop

Assuming I have two classes which are not related by inheritance. e.g:

class MyString
{
    private:
        std::string str;
};

class MyInt
{
    private:
        int num;
};

and I want to be able to convert one to another using regular casting e.g MyInt a = (MyInt)mystring (where mystring is of class MyString).

How does one accomplish such a thing?

like image 386
Jonathan Avatar asked Sep 07 '25 01:09

Jonathan


1 Answers

The conversion needs to make sense first of all. Assuming it does, you can implement your own conversion operators, like in the example below:

#include <string>
#include <iostream>

class MyInt; // forward declaration

class MyString
{
    std::string str;
public:
    MyString(const std::string& s): str(s){}
    /*explicit*/ operator MyInt () const; // conversion operator
    friend std::ostream& operator<<(std::ostream& os, const MyString& rhs)
    {
        return os << rhs.str;
    }
};

class MyInt
{
    int num;
public:
    MyInt(int n): num(n){}
    /*explicit*/ operator MyString() const{return std::to_string(num);} // conversion operator
    friend std::ostream& operator<<(std::ostream& os, const MyInt& rhs)
    {
        return os << rhs.num;
    }
};

// need the definition after MyInt is a complete type
MyString::operator MyInt () const{return std::stoi(str);} // need C++11 for std::stoi

int main()
{
    MyString s{"123"};
    MyInt i{42};

    MyInt i1 = s; // conversion MyString->MyInt
    MyString s1 = i; // conversion MyInt->MyString

    std::cout << i1 << std::endl;
    std::cout << s1 << std::endl;
}

Live on Coliru

If you mark the conversion operators as explicit, which is preferable (need C++11 or later), then you need to explicitly cast, otherwise the compiler will spit an error, like

MyString s1 = static_cast<MyString>(i1); // explicit cast
like image 187
vsoftco Avatar answered Sep 10 '25 01:09

vsoftco