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.
Class to class conversion using constructor in destination class:
A source class can be converted to a destination class by using a constructor in destination class which takes reference to source class.
Destination_class( source_class &object)
//assignments of members of destination class
//with members of source class using source class object
Class to class conversion using casting operator:
Class to class conversion is also possible using casting operator in source class. Operator type will be that of destination class.
A casting operator will be member function of source class anll return object of destination class.
//assignment of members of destination class with members of source class
//this function is member of source class hence it can access its other data members