Finding the object for which the constructor will be called while converting one class type to another class type
#include<iostream>
using namespace std;
class meter
{
private:
float m;
public:
meter()
{
m=0.0;
}
meter(float m1)
{
m=m1;
}
void display()
{
cout<<"the equivalient meter is "<<m<<endl;
}
};
class feet
{
private:
float f;
public:
void input()
{
cout<<"enter the value of feet"<<endl;
cin>>f;
}
operator meter()
{
float m1=f*0.3048;
return(meter(m1)); //line of interest
}
};
int main()
{
feet f2;
meter m2;
f2.input();
m2=f2; //type conversion call
m2.display();
return(0);
}
in the above mentioned code, in the line of interest; "return(meter(m1))" calls the constructor meter(float m1) for which object? I tried debugging and observing one step at a time, still could not figure out, I observed no new object being created. Is it for the object m2?
It's calling constructor of class meter
.
It creates temporary object.
It is unnamed object. More Informations here.
Your code will work like this.
m2 = f2.meter()
-
f2.meter()
returns temp object. m2.operator=(<temp object>)
meter m = meter(1.2);
This code is also using temporary object.
Check this code to check lifetime of temporary object.