How to convert a class to another class type in C++?

Pre-requisite: Type Conversion in C++, Advanced C++ | Conversion Operators

Through class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type.

Example:
Let there be two classes ‘A’ and ‘B’. If we want to allocate the details that belong to class ‘A’ to an object of class ‘B’ then this can be achieved by –



B(object of class B) = A(object of class A)
where ‘=’ has been overloaded for objects of class type ‘B’.

Class conversion can be achieved by conversion function which is done by the use of operator overloading.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
// Destination class, i.e
// Class to which another class to be converted
class Class_type_one {
    string a = "GeeksforGeeks";
  
public:
    // Member function which returns
    // string type data
    string get_string()
    {
        return (a);
    }
  
    // Member function to display
    void display()
    {
        cout << a << endl;
    }
};
  
// Source class, i.e
// Class type which will be converted
// to the destination class type
class Class_type_two {
    string b;
  
public:
    // Operator overloading which accepts data
    // of the Destination class and
    // assigns those data to the source class
    // Here it is for the conversion of
    // Class_type_two to Class_type_one
    void operator=(Class_type_one a)
    {
        b = a.get_string();
    }
  
    // Member function for displaying
    // the data assigned to b.
    void display()
    {
        cout << b << endl;
    }
};
  
int main()
{
    // Creating object of class Class_type_one
    Class_type_one a;
  
    // Creating object of class Class_type_two
    Class_type_two b;
  
    // CLass type conversion
    // using operator overloading
    b = a;
  
    // Displaying data of object
    // of class Class_type_one
    a.display();
  
    // Displaying data of object
    // of class Class_type_two
    b.display();
  
    return 0;
}

chevron_right


Output:

GeeksforGeeks
GeeksforGeeks


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.