2

I think, there is a common situation, when one function (a) is being called from within another one (b), while 'a' have some default parameters and 'b' is needed to support them. For example:

void a(int v1, int v2=0, int v3=1);
void b(int m1, int m2, int v1, int v2=0, int v3=1) {
    // ...
    a(v1, v2, v3);
    // ...
}

But this is the violation of the DRY principle. It can leads a subtile bug, when default parameter of 'a' was changed, but not changed in 'b':

void a(int v1, int v2, int v3=0);
void b(int m1, int m2, int v1, int v2=0, int v3=1) {
    // ...
    a(v1, v2, v3);
    // ...
}

Why there is no mechanism in C++ to inherit default parameter values? It might look like:

void a(int v1, int v2=0, int v3=1);
void b(int m1, int m2, int v1, int v2=default(a::v2, 0), int v3=default(a::v3, 1)) {
    // ...
    a(v1, v2, v3);
    // ...
}

Whether there are languages, that have such syntax?

It might be an offtopic on this board?

3
  • This wouldn't really be on-topic here, no. We tend more toward practical "this code isn't working" sorts of questions. Your question might be OK on Programmers.SE, but I can't be sure. The topic is definitely a better fit for them. Commented Aug 21, 2013 at 3:13
  • 4
    I removed the C tag because C does not have default parameters. Commented Aug 21, 2013 at 3:16
  • 1
    Well in C++ you could solve this issue by overloading b (with 3, 4 and 5 parameters). If you don't want to write the overloads yourself, you could use a variadic template / parameter pack. Alternatively, you could use something like a boost::optional as parameter (for b) with a default argument. Commented Aug 21, 2013 at 3:36

2 Answers 2

5

The issue is actually the use of magic numbers. If you remove the magic numbers, the problem is resolved nicely.

enum DefaultA { DefaultA_v2 = 0, DefaultA_v3 = 1 };

void a(int v1, int v2=DefaultA_v2, int v3=DefaultA_v3);

void b(int m1, int m2, int v1, int v2=DefaultA_v2, int v3=DefaultA_v3) {
    // ...
    a(v1, v2, v3);
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

And once again, another level of indirection solves the problem.
0

"But this is the violation of the DRY principle. It can leads a subtile bug, when default parameter of 'a' was changed, but not changed in 'b'"

Frankly, I'd say that if you get this "bug", then your functions are too tightly-coupled. Standalone functions are supposed to, well, stand alone. If changing a default parameter for one function causes another function to break, I think you have a design problem there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.