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

In this tutorial, we will be discussing a program to understand how to convert a class to another class type in C/C++.

Class conversion can be done with the help of operator overloading. This allows data of one class type to be assigned to the object of another class type.

Example

#include <bits/stdc++.h>
using namespace std;
//type to which it will be converted
class Class_type_one {
   string a = "TutorialsPoint";
   public:
      string get_string(){
         return (a);
   }
   void display(){
      cout << a << endl;
   }
};
//class to be converted
class Class_type_two {
   string b;
   public:
   void operator=(Class_type_one a){
      b = a.get_string();
   }
   void display(){
      cout << b << endl;
   }
};
int main(){
   //type one
   Class_type_one a;
   //type two
   Class_type_two b;
   //type conversion
   b = a;
   a.display();
   b.display();
   return 0;
}

Output

TutorialsPoint
TutorialsPoint
Updated on: 2026-03-11T22:50:48+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements