• My previous post was dedicated for “Basic to Class Type” conversion. If you haven’t read yet, I strongly recommend you to read that first before proceeding to this post.  In this post, I am going to teach you how conversion from class type to basic type can be achieved.
  • In this type of conversion the source type is class type and the destination type is basic type. Means  class data type is converted into the basic type.
  • For example we have class Time and one object of Time class ‘t’ and suppose we want to assign the total time of object ‘t’ to any integer variable say ‘duration’ then the statement below is the example of the conversion from class to basic type.
duration= t ; // where, t is object and duration is of basic data type
  • Here the assignment will be done by converting “t” object which is of class type into the basic or primary data type. It requires special casting operator function for class type to basic type conversion. This is known as the conversion function. The syntax for the conversion function is as under:
  operator typename( )
  {
       ….
       ….
       ….
  }
  • For example suppose we want to assign time in hours and minutes in the form of total time in minutes into one integer variable “duration” then we can write the type conversion function as under:
/* Program to demonstrate Class type to Basic type conversion. */

#include "iostream.h"
#include "conio.h"
#include "iomanip.h"

class Time
{
	int hrs,min;
	public:
		Time(int ,int);   // constructor
		operator int();   // casting operator function
		~Time()          // destructor
		{
			cout<<"Destructor called..."<<endl;
		}
};

Time::Time(int a,int b)
{
	cout<<"Constructor called with two parameters..."<<endl;
	hrs=a;
	min=b;
}

Time :: operator int()
{
	cout<<"Class Type to Basic Type Conversion..."<<endl;
	return(hrs*60+min);
}

void main()
{
	clrscr();
	int h,m,duration;
	cout<<"Enter Hours ";
        cin>>h;
	cout<<"Enter Minutes ";
        cin>>m;
	Time t(h,m);       // construct object
	duration = t;      // casting conversion OR duration = (int)t
	cout<<"Total Minutes are "<<duration;
	cout<<"2nd method operator overloading "<<endl;
	duration = t.operator int();
	cout<<"Total Minutes are "<<duration;
	
        getch();
}
  • Notice the statement in above program where conversion took place.
      duration = t;
  • We can also specify the casting type and write the same statement by the following way to achieve the same result.
    duration = (int) t;          // Casting
  • The conversion function should satisfy the following condition:
  1. It must be a class member.
  2. It must not specify the return value even though it returns the value.
  3. It must not have any argument.