Reputation: 17
// Example program
#include <iostream>
#include <string>
using namespace std;
class circle {
private:
double r;
double const pi=3.14;
public:
circle(double rad){
r=rad;
}
void periArea(){
double p,s;
p=2*pi*r;
s=pi*pi*r;
cout<<"\nS= "<<s<<endl;
cout<<"\nP= "<<p<<endl;
}
friend void changeRad(circle circle, double newrad);
};
void changeRad(circle circle, double newrad){
circle.r=newrad;
}
int main()
{
double inpr,newr;
cout<<"input radius: ";
cin>>inpr;
circle c1(inpr);
c1.periArea();
cout<<"\ninput new radius: ";
cin>>newr;
changeRad(c1,newr);
c1.periArea();
}
I've got this cpp code that has to define a class circle that calculates perimeter and area then using a friend function change the radius and calculate the area and perimeter again. However I get the same p and s values even after the change function.
Upvotes: 1
Views: 91
Reputation: 310930
You have to pass an object the type Circle by reference
friend void changeRad( circle &circle, double newrad);
^^^
Take into account that though it is a valid declaration of a parameter when its name coincides with the name of the type nevertheless this can confuse the reader and the name of the parameter hides the name of the type. So it is better to rename the name of the parameter as for example
friend void changeRad( circle &c, double newrad);
^^
Also it is better to make the function a non-static member of the class. For example
void changeRad( double newrad );
Upvotes: 1
Reputation: 234655
Crudely, you need to change your function to pass the circle by reference:
void changeRad(circle& circle, double newrad){
(Note the use of &
). Otherwise a copy of the circle
instance is passed to the function and any changes to that copy will not be reflected in the original.
But, the normal way of doing things is to arrange your code so that you use
c1.changeRad(newr);
at the call site.
Also, your use of a double
to store pi to just 3 significant figures is pretty terrible. My favourite way is to use
const double PI = std::atan(1.0) * 4;
since the C++ standard does not define pi for you (M_PI
is POSIX, not ISO!).
Upvotes: 6