Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if the default parameter value is defined in code not visible at the call site?

Tags:

c++

header

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?

like image 479
sharptooth Avatar asked Jul 17 '09 09:07

sharptooth


People also ask

Where do default parameters appear?

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.

Where should the default value of parameter is specified?

We can provide a default value to a particular argument in the middle of an argument list. C.

What is default parameter can we use default parameter for first parameter in function?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

How do you define the default value of a function parameter?

ECMAScript 2015 allows default parameter values in the function declaration: function myFunction (x, y = 2) { // function code. } Try it Yourself »


1 Answers

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
like image 133
mmx Avatar answered Sep 21 '22 21:09

mmx