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.

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.






#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";
    // 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;
    // 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
    // Displaying data of object
    // of class Class_type_two
    return 0;




Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.

My Personal Notes arrow_drop_up

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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.

Article Tags :
Practice Tags :


Please write to us at to report any issue with the above content.