Peaceful
Peaceful

Reputation: 480

what are the restricitons of the type of a default parameter in C++

void foo(Type1 a, Type2 b = value2)

May I know what are the restrictions of Type2 to be a parameter that accepts default value? I reckon value2 of type2 should be decidable at compile time. For example, an integer. Is this correct?

Upvotes: 1

Views: 75

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279255

You have quite a lot of flexibility. value2 needs to be an expression which is valid at the point of declaration of the function (by "valid" I mean that the names it uses are in scope, etc), and its type must be implicitly convertible to Type2, same as for any initializer. value2 is evaluated each time the function is called. So for example:

#include <vector>
#include <iostream>

int i;

void foo(std::vector<int> v = std::vector<int>(i)) {
    std::cout << v.size() << "\n";
}

int main() {
    i = 1;
    foo();
    i = 2;
    foo();
}

With the right initializer, Type2 can even be a reference type:

void bar(int &j = i);

Upvotes: 1

Digital_Reality
Digital_Reality

Reputation: 4738

Yes correct.

The only limitation is defaulted variable should be last one. You can have multiple default variables just make sure keep them all at the end. Don't mix with non default ones.

Upvotes: 0

John Dibling
John Dibling

Reputation: 101456

value2 must be compile-time convertible to Type2.

Upvotes: 1

Related Questions