Reputation: 13
i have a little question, how can i initialize default arguments in an function?
#include <iostream>
#include <cmath>
using namespace std;
float area(float a, float b, float c);
float area(float a, float b=a, float c =a);
int main() {
cout << area(10) << endl;
return 0;
}
float area(float a, float b, float c){
return a*b*c
}
i am getting errors, how can i impelent correctly?
Upvotes: 1
Views: 1141
Reputation: 48258
In C++
you should prototype and implement the code for only one method including the optional parameters and the default values is the optional parameter is ommitted must be a constant and not an unknown value...
float area(float a, float b=0, float c=0);
int main() {
cout << area(10) << endl;
return 0;
}
float area(float a, float b=-1, float c =-1);){
if(b==-1 ||c==-1)
{
return a*a*a;
}else
{
return a*b*c;
}
}
Upvotes: 0
Reputation: 49976
If you want default value for b
and c
to be the value of a
then you should use overloading:
float area(float a, float b, float c){
return a*b*c
}
float area(float a) {
return area(a, a, a);
}
C++ does not allow to use parameters as default arguments. So this
float area(float a, float b=a, float c =a);
^^ ^^
is an Error.
Upvotes: 1
Reputation: 37806
You are going to have to use overloading instead of default parameters:
#include <iostream>
#include <cmath>
using namespace std;
float area(float a, float b, float c);
float area(float a);
int main() {
cout << area(10) << endl;
return 0;
}
float area(float a, float b, float c){
return a*b*c;
}
float area(float a){
return area(a,a,a);
}
Upvotes: 3