### Initializing a variable in the function argument is giving me an error

For this code below, I am getting these errors:

default argument given for parameter 1 of `void Point::print(double)'
after previous specification in `void Point::print(double)'

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576`` ``````#include #include using namespace std; class Point{ private: double x; double y; public: Point(void); Point(double xinit, double yinit); void print(double factor=1.0); void move(double dx, double dy); void moveto(double xnew, double ynew); double from_origin(void); double get_x(void); double get_y(void); }; Point::Point(){ x=0; y=0;} Point::Point(double xinit, double yinit){ x=xinit; y=yinit; } void Point::print(double factor=1.0){ //factor=1.0; cout << "(" << x*factor << "," << y*factor << ")"; } void Point::move(double dx, double dy){ x+=dx; y+=dy; } void Point::moveto(double xnew, double ynew){ xnew=x; ynew=y; } double Point::from_origin(void){ return sqrt(x*x+y*y); } double Point::get_x(void){ return x; } double Point::get_y(void){ return y; } int main(){ Point p1; Point p2(2,2); cout<<"p1 is : "; p1.print(); cout< p2.from_origin() ) cout<<"p1"; else cout<<"p2 "; cout<<"is farther away from the origin (0,0)\n"<

When I replace the line:

" void Point::print(double factor=1.0){ "

with :

" void Point::print(double factor){
factor=1.0; "

It works. Can someone tell me why the code didn't work before? And if there is a better way of writing it.

You only need to include default parameters in the definition of the function, not the declaration. (At least in this example with classes).

Remove the 1.0 from
 ``1234`` ``````void Point::print(double factor=1.0){ //factor=1.0; cout << "(" << x*factor << "," << y*factor << ")"; }``````
Last edited on
well for one thing, if you're passing a double value to Point::print(double factor)
why would you then want to assign a literal const value (1.0) to factor?
it should be taking that argument from the callback.. otherwise it should just be:

void Point::print()
{
double factor = 1.0;
}

but I know that's not what you want either..
Last edited on
Thanks! That makes more sense!
You're welcome!
If you're still following this.. I wonder if you should declare "factor" as a `const double` with yer private doubles x and y ^ in lines 8 and 9, instead of the function definition.

`void Point::print(double factor=1.0)`
maybe change that to this:
`void Point::print()`

then lines 28 - 31 could look more like this:
 ``1234`` ``````void Point::print(){ //factor=1.0; cout << "(" << x*factor << "," << y*factor << ")"; }``````

Just tryn to streamline.
If I'm doing anything bad, someone please kindly let me know.
Last edited on
Topic archived. No new replies allowed.