I've found some strange code...
//in file ClassA.h:
class ClassA {
public:
void Enable( bool enable );
};
//in file ClassA.cpp
#include <ClassA.h>
void ClassA::Enable( bool enable = true )
{
//implementation is irrelevant
}
//in Consumer.cpp
#include <ClassA.h>
....
ClassA classA;
classA.Enable( true );
Obviously since Consumer.cpp
only included ClassA.h
and not ClassA.cpp
the compiler will not be able to see that the parameter has a default value.
When would the declared default value of ClassA::Enable
in the signature of the method implementation have any effect? Would this only happen when the method is called from within files that include the ClassA.cpp
?
Default parameter values must appear on the declaration, since that is the only thing that the caller sees. EDIT: As others point out, you can have the argument on the definition, but I would advise writing all code as if that wasn't true.
We can provide a default value to a particular argument in the middle of an argument list. C.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
ECMAScript 2015 allows default parameter values in the function declaration: function myFunction (x, y = 2) { // function code. } Try it Yourself »
Default values are just a compile time thing. There's no such thing as default value in compiled code (no metadata or things like that). It's basically a compiler replacement for "if you don't write anything, I'll specify that for you." So, if the compiler can't see the default value, it assumes there's not one.
Demo:
// test.h
class Test { public: int testing(int input); };
// main.cpp
#include <iostream>
// removing the default value here will cause an error in the call in `main`:
class Test { public: int testing(int input = 42); };
int f();
int main() {
Test t;
std::cout << t.testing() // 42
<< " " << f() // 1000
<< std::endl;
return 0;
}
// test.cpp
#include "test.h"
int Test::testing(int input = 1000) { return input; }
int f() { Test t; return t.testing(); }
Test:
g++ main.cpp test.cpp
./a.out
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