why my code does not work when i call the gett function and try to print the output(second code) where as it gives proper output when i pass the argument from main(first code). I called my function using rs.power(arguments) in first and in second using get function i am getting - output in the second code
code-1
#include<iostream>
#include<cmath>
using namespace std;
class powm
{
public:
double result;
public:
inline power(double m,double n)
{
result=pow(m,n);
}
void display()
{
cout<<result;
}
}rs;
int main()
{
double a,b;
cout<<"We are calculating the power of the number "<<endl;
cout<<"Enter the number :"<<endl;
cin>>a;
cout<<"enter the power :"<<endl;
cin>>b;
rs.power(a,b);
rs.display();
return 0;
}
Code-2
#include<iostream>
#include<cmath>
using namespace std;
class powm
{
public:
double result,a,b;
public:
void gett()
{
cout<<"We are calculating the power of the number "<<endl;
cout<<"Enter the number :"<<endl;
cin>>a;
cout<<"enter the power :"<<endl;
cin>>b;
}
inline power()
{
result=pow(a,b);
}
void display()
{
cout<<result;
}
}rs;
int main()
{
rs.gett();
rs.display();
return 0;
}
In the second code block, you haven't done anything to compute result
.
Try
rs.gett();
rs.power();
rs.display();
I would recommend using:
#include <iostream>
#include <cmath>
using namespace std;
class powm
{
public:
double result;
public:
// Make sure constructor initializes the member variables appropriately.
powm(double m,double n) : result(pow(m,n)) {}
};
// Separate display to a non-member function.
// Make it general and not hard coded to output to cout.
std::ostream& operator<<(std::ostream& out, powm const& p)
{
return out << p.result;
}
int main()
{
double a,b;
cout<<"We are calculating the power of the number "<<endl;
cout<<"Enter the number :"<<endl;
cin>>a;
cout<<"enter the power :"<<endl;
cin>>b;
// Construct object.
powm rs(a,b);
// Display to cout.
cout << rs << ened;
return 0;
}