I have a problem with specifying the default values for my C++ class members. My code is:
From Someclass.h:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool);
}
...from SomeClass.cpp:
void SomeClass::printOut(bool foobar=true)
{
if (foobar) { std::cout << foobar << std::endl; }
}
...and finally, from main.cpp:
int main()
{
SomeClass s;
s.printOut();
return 0;
}
This however gives error message (gcc):
../main.cpp: In function `int main()':
../main.cpp:8: error: no matching function for call to `SomeClass::printOut()'
../SomeClass.h:18: note: candidates are: void SomeClass::printOut(bool)
subdir.mk:21: recipe for target `main.o' failed
make: *** [main.o] Error 1
I have tried specifying the default value directly into the class declaration in the header file, etc. I also tried searching both Stack Overflow and Google in general, but cannot find any solution anywhere. What am I doing wrong?
You haven't specified the default value for the parameter in the header as such, the compiler is looking for a function of signature void printOut(void)
for your statement s.printOut();
but correctly not finding it. What you need is:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut( bool fValue = true ); // Note change in param in definition
}
And in your cpp :
void SomeClass::printOut(bool foobar /*=true*/ )
{
if (foobar) { std::cout << foobar << std::endl; }
}
As a side note, bear in mind you don't have to put the commented out default value for the parameter in the implementation file but it is a good idea for readability.
You need to declare the default value inside the class definition, not in the implementation.
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool foobar = true); //move default here
}
void SomeClass::printOut(bool foobar) //remove from here
{
if (foobar) { std::cout << foobar << std::endl; }
}
Also, note that:
SomeClass s();
doesn't do what you expect it to do. It doesn't create an object s
of type SomeClass
, but declares a function s
with return type SomeClass
. s.printOut();
shouldn't compile.
You probably want:
SomeClass s;
Default value must be specified in the declaration of the method, not in the implementation.
Try to specify default value in header file:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool foobar=true);
}
Default parameters must be defined in the header like this:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool value = true);
}
rewrite as follow .. note bool b=false
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool b=false);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With