Skip to content
Related Articles

Related Articles

How to convert a class to another class type in C++?
  • Difficulty Level : Easy
  • Last Updated : 05 Mar, 2019

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:




#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;
}
Output:
GeeksforGeeks
GeeksforGeeks
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :