[dcl.decl] (original) (raw)
9.3.1 Type names [dcl.name]
To specify type conversions explicitly,and as an argument ofsizeof,alignof,new, ortypeid, the name of a type shall be specified.
This can be done with atype-id, which is syntactically a declaration for a variable or function of that type that omits the name of the entity.
type-id: type-specifier-seq abstract-declarator
defining-type-id: defining-type-specifier-seq abstract-declarator
abstract-declarator: ptr-abstract-declarator noptr-abstract-declarator parameters-and-qualifiers trailing-return-type abstract-pack-declarator
ptr-abstract-declarator: noptr-abstract-declarator ptr-operator ptr-abstract-declarator
noptr-abstract-declarator: noptr-abstract-declarator parameters-and-qualifiers noptr-abstract-declarator [ constant-expression ] attribute-specifier-seq ( ptr-abstract-declarator )
abstract-pack-declarator: noptr-abstract-pack-declarator ptr-operator abstract-pack-declarator
noptr-abstract-pack-declarator: noptr-abstract-pack-declarator parameters-and-qualifiers noptr-abstract-pack-declarator [ constant-expression ] attribute-specifier-seq ...
It is possible to identify uniquely the location in theabstract-declaratorwhere the identifier would appear if the construction were a declarator in a declaration.
The named type is then the same as the type of the hypothetical identifier.
[ Example
:
int
int *
int [3]
int ()[3]
int ()
int ()(double)
name respectively the types “int”, “pointer toint”, “array of 3 pointers toint”, “pointer to array of 3int”, “function of (no parameters) returning pointer toint”, and “pointer to a function of (double) returningint”.
— end example
]
A type can also be named (often more easily) by using atypedef ([dcl.typedef]).
9.3.2 Ambiguity resolution [dcl.ambig.res]
The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in [stmt.ambig] can also occur in the context of a declaration.
In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer.
Just as for the ambiguities mentioned in [stmt.ambig], the resolution is to consider any construct that could possibly be a declaration a declaration.
[ Note
:
A declaration can be explicitly disambiguated by adding parentheses around the argument.
The ambiguity can be avoided by use of copy-initialization or list-initialization syntax, or by use of a non-function-style cast.
— end note
]
[ Example
:
struct S { S(int); };
void foo(double a) {
S w(int(a));
S x(int());
S y((int(a)));
S y((int)a);
S z = int(a);
}
— end example
]
An ambiguity can arise from the similarity between a function-style cast and atype-id.
The resolution is that any construct that could possibly be atype-idin its syntactic context shall be considered atype-id.
[ Example
:
template struct X {};
template struct Y {};
X<int()> a;
X<int(1)> b;
Y<int()> c;
Y<int(1)> d;
void foo(signed char a) {
sizeof(int());
sizeof(int(a));
sizeof(int(unsigned(a)));
(int())+1;
(int(a))+1;
(int(unsigned(a)))+1;
}
— end example
]
Another ambiguity arises in aparameter-declaration-clause when atype-nameis nested in parentheses.
In this case, the choice is between the declaration of a parameter of type pointer to function and the declaration of a parameter with redundant parentheses around thedeclarator-id.
[ Example
:
class C { }; void f(int(C)) { }
int g(C);
void foo() {
f(1);
f(g);
}
For another example,
class C { }; void h(int *(C[10]));
— end example
]
9.3.3 Meaning of declarators [dcl.meaning]
A declarator contains exactly onedeclarator-id; it names the identifier that is declared.
When thedeclarator-idis qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers (or, in the case of a namespace, of an element of the inline namespace set of that namespace ([namespace.def])) or to a specialization thereof; the member shall not merely have been introduced by ausing-declarationin the scope of the class or namespace nominated by thenested-name-specifierof thedeclarator-id.
[ Note
:
If the qualifier is the global::scope resolution operator, thedeclarator-idrefers to a name declared in the global namespace scope.
— end note
]
Following is a recursive procedure for determining the type specified for the containeddeclarator-idby such a declaration.
[ Example
:
In the declaration
int unsigned i;
the type specifiersint unsigneddetermine the type “unsigned int” ([dcl.type.simple]).
— end example
]
In a declarationT DwhereDhas the form
( D1 )
the type of the containeddeclarator-idis the same as that of the containeddeclarator-idin the declaration
T D1
Parentheses do not alter the type of the embeddeddeclarator-id, but they can alter the binding of complex declarators.
9.3.3.1 Pointers [dcl.ptr]
In a declarationT DwhereDhas the form
and the type of the identifier in the declarationT D1is “derived-declarator-type-list T”, then the type of the identifier ofDis “derived-declarator-type-list cv-qualifier-seq pointer toT”.
Thecv-qualifiersapply to the pointer and not to the object pointed to.
Similarly, the optional attribute-specifier-seq appertains to the pointer and not to the object pointed to.
[ Example
:
The declarations
const int ci = 10, *pc = &ci, *const cpc = pc, **ppc; int i, *p, *const cp = &i;
declareci, a constant integer;pc, a pointer to a constant integer;cpc, a constant pointer to a constant integer;ppc, a pointer to a pointer to a constant integer;i, an integer;p, a pointer to integer; andcp, a constant pointer to integer.
The value ofci,cpc, andcpcannot be changed after initialization.
The value ofpccan be changed, and so can the object pointed to bycp.
Examples of some correct operations are
i = ci; *cp = ci; pc++; pc = cpc; pc = p; ppc = &pc;
Examples of ill-formed operations are
ci = 1;
ci++;
*pc = 2;
cp = &ci;
cpc++;
p = pc;
ppc = &p;
Each is unacceptable because it would either change the value of an object declaredconstor allow it to be changed through a cv-unqualified pointer later, for example:
*ppc = &ci;
*p = 5;
— end example
]
[ Note
:
Forming a pointer to reference type is ill-formed; see [dcl.ref].
Forming a function pointer type is ill-formed if the function type hascv-qualifiers or a ref-qualifier; see [dcl.fct].
Since the address of a bit-field ([class.bit]) cannot be taken, a pointer can never point to a bit-field.
— end note
]
9.3.3.2 References [dcl.ref]
In a declarationT DwhereDhas either of the forms
& attribute-specifier-seq D1 && attribute-specifier-seq D1
and the type of the identifier in the declarationT D1is “derived-declarator-type-list T”, then the type of the identifier ofDis “derived-declarator-type-list reference toT”.
[ Example
:
typedef int& A; const A aref = 3;
The type ofarefis “lvalue reference to int”, not “lvalue reference to const int”.
— end example
]
[ Note
:
A reference can be thought of as a name of an object.
— end note
]
A declarator that specifies the type “reference to cv void” is ill-formed.
A reference type that is declared using & is called anlvalue reference, and a reference type that is declared using && is called anrvalue reference.
Lvalue references and rvalue references are distinct types.
Except where explicitly noted, they are semantically equivalent and commonly referred to as references.
[ Example
:
void f(double& a) { a += 3.14; }
double d = 0; f(d);
declaresato be a reference parameter offso the callf(d)will add3.14tod.
int v[20];
int& g(int i) { return v[i]; }
g(3) = 7;
declares the functiong()to return a reference to an integer sog(3)=7will assign7to the fourth element of the arrayv.
For another example,
struct link { link* next; };
link* first;
void h(link*& p) {
p->next = first;
first = p;
p = 0;
}
void k() { link* q = new link; h(q); }
declarespto be a reference to a pointer tolinksoh(q)will leaveqwith the value zero.
— end example
]
It is unspecified whether or not a reference requires storage ([basic.stc]).
There shall be no references to references, no arrays of references, and no pointers to references.
The declaration of a reference shall contain aninitializer ([dcl.init.ref]) except when the declaration contains an explicitexternspecifier ([dcl.stc]), is a class member ([class.mem]) declaration within a class definition, or is the declaration of a parameter or a return type ([dcl.fct]); see [basic.def].
A reference shall be initialized to refer to a valid object or function.
[ Note
:
In particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by indirection through a null pointer, which causes undefined behavior.
As described in [class.bit], a reference cannot be bound directly to a bit-field.
— end note
]
If a typedef-name ([dcl.typedef], [temp.param]) or a decltype-specifier ([dcl.type.simple]) denotes a type TR that is a reference to a type T, an attempt to create the type “lvalue reference to cv TR” creates the type “lvalue reference to T”, while an attempt to create the type “rvalue reference to cv TR” creates the type TR.
[ Note
:
This rule is known as reference collapsing.
— end note
]
[ Example
:
int i; typedef int& LRI; typedef int&& RRI;
LRI& r1 = i;
const LRI& r2 = i;
const LRI&& r3 = i;
RRI& r4 = i;
RRI&& r5 = 5;
decltype(r2)& r6 = i;
decltype(r2)&& r7 = i;
— end example
]
[ Note
:
Forming a reference to function type is ill-formed if the function type has cv-qualifiers or a ref-qualifier; see [dcl.fct].
— end note
]
9.3.3.3 Pointers to members [dcl.mptr]
[ Example
:
struct X { void f(int); int a; }; struct Y;
int X::* pmi = &X::a; void (X::* pmf)(int) = &X::f; double X::* pmd; char Y::* pmc;
declarespmi,pmf,pmdandpmcto be a pointer to a member ofXof typeint, a pointer to a member ofXof typevoid(int), a pointer to a member ofXof typedoubleand a pointer to a member ofYof typecharrespectively.
The declaration ofpmdis well-formed even thoughXhas no members of typedouble.
Similarly, the declaration ofpmcis well-formed even thoughYis an incomplete type.
pmiandpmfcan be used like this:
X obj;
obj.*pmi = 7;
(obj.*pmf)(7);
— end example
]
A pointer to member shall not point to a static member of a class ([class.static]), a member with reference type, or “cv void”.
[ Note
:
The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer-to-member declarator syntax, and never by the pointer declarator syntax.
There is no “reference-to-member” type in C++.
— end note
]
9.3.3.4 Arrays [dcl.array]
In a declaration T D where D has the form
D1 [ constant-expression ] attribute-specifier-seq
and the type of the contained declarator-idin the declaration T D1is “derived-declarator-type-list T”, the type of the declarator-id in D is “derived-declarator-type-list array of N T”.
Its value N specifies the array bound, i.e., the number of elements in the array;N shall be greater than zero.
In a declaration T D where D has the form
D1 [ ] attribute-specifier-seq
and the type of the contained declarator-idin the declaration T D1is “derived-declarator-type-list T”, the type of the declarator-id in D is “derived-declarator-type-list array of unknown bound of T”, except as specified below.
A type of the form “array of N U” or “array of unknown bound of U” is an array type.
U is called the array element type; this type shall not be a placeholder type ([dcl.spec.auto]), a reference type, a function type, an array of unknown bound, orcv void.
[ Note
:
An array can be constructed from one of the fundamental types (except void), from a pointer, from a pointer to member, from a class, from an enumeration type, or from an array of known bound.
— end note
]
[ Example
:
float fa[17], *afp[17];
declares an array of float numbers and an array of pointers to float numbers.
— end example
]
Any type of the form “cv-qualifier-seq array of N U” is adjusted to “array of N cv-qualifier-seq U”, and similarly for “array of unknown bound of U”.
[ Example
:
typedef int A[5], AA[2][3];
typedef const A CA;
typedef const AA CAA;
— end example
]
An object of type “array of N U” contains a contiguously allocated non-empty set of N subobjects of type U, known as the elements of the array, and numbered 0 to N-1.
In addition to declarations in which an incomplete object type is allowed, an array bound may be omitted in some cases in the declaration of a function parameter ([dcl.fct]).
An array bound may also be omitted when an object (but not a non-static data member) of array type is initialized and the declarator is followed by an initializer ([dcl.init], [class.mem], [expr.type.conv], [expr.new]).
In these cases, the array bound is calculated from the number of initial elements (say, N) supplied ([dcl.init.aggr]), and the type of the array is “array of N U”.
Furthermore, if there is a preceding declaration of the entity in the same scope in which the bound was specified, an omitted array bound is taken to be the same as in that earlier declaration, and similarly for the definition of a static data member of a class.
[ Example
:
extern int x[10]; struct S { static int y[10]; };
int x[];
int S::y[];
void f() {
extern int x[];
int i = sizeof(x);
}
— end example
]
[ Note
:
When several “array of” specifications are adjacent, a multidimensional array type is created; only the first of the constant expressions that specify the bounds of the arrays may be omitted.
[ Example
:
int x3d[3][5][7];
declares an array of three elements, each of which is an array of five elements, each of which is an array of seven integers.
The overall array can be viewed as a three-dimensional array of integers, with rank .
Any of the expressionsx3d,x3d[i],x3d[i][j],x3d[i][j][k]can reasonably appear in an expression.
The expressionx3d[i]is equivalent to*(x3d + i); in that expression,x3dis subject to the array-to-pointer conversion ([conv.array]) and is first converted to a pointer to a 2-dimensional array with rankthat points to the first element of x3d.
Then i is added, which on typical implementations involves multiplyingi by the length of the object to which the pointer points, which is sizeof(int).
The result of the addition and indirection is an lvalue denoting the array element ofx3d(an array of five arrays of seven integers).
If there is another subscript, the same argument applies again, sox3d[i][j] is an lvalue denoting the array element of the array element ofx3d(an array of seven integers), andx3d[i][j][k] is an lvalue denoting the array element of the array element of the array element ofx3d(an integer).
— end example
]
The first subscript in the declaration helps determine the amount of storage consumed by an array but plays no other part in subscript calculations.
— end note
]
[ Note
:
Conversions affecting expressions of array type are described in [conv.array].
— end note
]
[ Note
:
The subscript operator can be overloaded for a class ([over.sub]).
For the operator's built-in meaning, see [expr.sub].
— end note
]
9.3.3.5 Functions [dcl.fct]
In a declarationT DwhereDhas the form
D1 ( parameter-declaration-clause ) cv-qualifier-seq ref-qualifier noexcept-specifier attribute-specifier-seq
and the type of the containeddeclarator-idin the declarationT D1is “derived-declarator-type-list T”, the type of thedeclarator-idinDis “derived-declarator-type-list noexceptfunction of parameter-type-listcv-qualifier-seq ref-qualifierreturning T”, where
- the parameter-type-list is derived from the parameter-declaration-clause as described below and
- the optional noexcept is present if and only if the exception specification ([except.spec]) is non-throwing.
The type of thedeclarator-idinDis “derived-declarator-type-list noexceptfunction of parameter-type-listcv-qualifier-seq ref-qualifierreturning U”, where
- the parameter-type-list is derived from the parameter-declaration-clause as described below,
- U is the type specified by the trailing-return-type, and
- the optional noexcept is present if and only if the exception specification is non-throwing.
Theparameter-declaration-clausedetermines the arguments that can be specified, and their processing, when the function is called.
[ Note
:
Theparameter-declaration-clauseis used to convert the arguments specified on the function call; see [expr.call].
— end note
]
If theparameter-declaration-clauseis empty, the function takes no arguments.
A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
Except for this special case, a parameter shall not have type cv void.
If theparameter-declaration-clause terminates with an ellipsis or a function parameter pack ([temp.variadic]), the number of arguments shall be equal to or greater than the number of parameters that do not have a default argument and are not function parameter packs.
Where syntactically correct and where “...” is not part of an abstract-declarator, “, ...” is synonymous with “...”.
[ Example
:
The declaration
int printf(const char*, ...);
declares a function that can be called with varying numbers and types of arguments.
printf("hello world"); printf("a=%d b=%d", a, b);
However, the first argument must be of a type that can be converted to aconst char*.
— end example
]
The type of a function is determined using the following rules.
The type of each parameter (including function parameter packs) is determined from its owndecl-specifier-seqanddeclarator.
After determining the type of each parameter, any parameterof type “array of T” orof function type Tis adjusted to be “pointer to T”.
After producing the list of parameter types, any top-levelcv-qualifiersmodifying a parameter type are deleted when forming the function type.
The resulting list of transformed parameter types and the presence or absence of the ellipsis or a function parameter pack is the function'sparameter-type-list.
[ Note
:
This transformation does not affect the types of the parameters.
For example, int(*)(const int p, decltype(p)*) andint(*)(int, const int*) are identical types.
— end note
]
[ Example
:
typedef int FIC(int) const;
FIC f;
struct S {
FIC f;
};
FIC S::*pm = &S::f;
— end example
]
The effect of acv-qualifier-seqin a function declarator is not the same as adding cv-qualification on top of the function type.
In the latter case, the cv-qualifiers are ignored.
[ Note
:
A function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types.
— end note
]
[ Example
:
typedef void F();
struct S {
const F f;
};
— end example
]
The return type, the parameter-type-list, the ref-qualifier, the cv-qualifier-seq, and the exception specification, but not the default arguments ([dcl.fct.default]) or the trailing requires-clause ([dcl.decl]), are part of the function type.
[ Note
:
Function types are checked during the assignments and initializations of pointers to functions, references to functions, and pointers to member functions.
— end note
]
[ Example
:
The declaration
int fseek(FILE*, long, int);
declares a function taking three arguments of the specified types, and returningint ([dcl.type]).
— end example
]
A single name can be used for several different functions in a single scope; this is function overloading ([over]).
All declarations for a function shall have equivalent return types, parameter-type-lists, and requires-clauses ([temp.over.link]).
Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.
There shall be no arrays of functions, although there can be arrays of pointers to functions.
Types shall not be defined in return or parameter types.
A typedef of function type may be used to declare a function but shall not be used to define a function ([dcl.fct.def]).
[ Example
:
typedef void F();
F fv;
F fv { }
void fv() { }
— end example
]
An identifier can optionally be provided as a parameter name; if present in a function definition ([dcl.fct.def]), it names a parameter.
[ Note
:
In particular, parameter names are also optional in function definitions and names used for a parameter in different declarations and the definition of a function need not be the same.
If a parameter name is present in a function declaration that is not a definition, it cannot be used outside of its function declarator because that is the extent of its potential scope ([basic.scope.param]).
— end note
]
[ Example
:
The declaration
int i, *pi, f(), fpi(int), (pif)(const char, const char), (*fpif(int))(int);
declares an integeri, a pointerpito an integer, a functionftaking no arguments and returning an integer, a functionfpitaking an integer argument and returning a pointer to an integer, a pointerpifto a function which takes two pointers to constant characters and returns an integer, a functionfpiftaking an integer argument and returning a pointer to a function that takes an integer argument and returns an integer.
It is especially useful to comparefpiandpif.
The binding of*fpi(int)is*(fpi(int)), so the declaration suggests, and the same construction in an expression requires, the calling of a functionfpi, and then using indirection through the (pointer) result to yield an integer.
In the declarator(*pif)(const char*, const char*), the extra parentheses are necessary to indicate that indirection through a pointer to a function yields a function, which is then called.
— end example
]
[ Note
:
Typedefs and trailing-return-types are sometimes convenient when the return type of a function is complex.
For example, the functionfpifabove could have been declared
typedef int IFUNC(int); IFUNC* fpif(int);
or
auto fpif(int)->int(*)(int);
A trailing-return-type is most useful for a type that would be more complicated to specify before the declarator-id:
template <class T, class U> auto add(T t, U u) -> decltype(t + u);
rather than
template <class T, class U> decltype(((T)0) + ((U)0)) add(T t, U u);
— end note
]
A non-template function is a function that is not a function template specialization.
[ Note
:
A function template is not a function.
— end note
]
An abbreviated function templateis a function declaration that has one or more generic parameter type placeholders ([dcl.spec.auto]).
An abbreviated function template is equivalent to a function template ([temp.fct]) whose template-parameter-list includes one invented type template-parameterfor each generic parameter type placeholder of the function declaration, in order of appearance.
The invented type template-parameter is a template parameter pack if the corresponding parameter-declarationdeclares a function parameter pack ([dcl.fct]).
If the placeholder contains decltype(auto), the program is ill-formed.
The adjusted function parameters of an abbreviated function template are derived from the parameter-declaration-clause by replacing each occurrence of a placeholder with the name of the corresponding invented template-parameter.
[ Example
:
template concept C1 = ; template concept C2 = ; template<typename... Ts> concept C3 = ;
void g1(const C1 auto*, C2 auto&); void g2(C1 auto&...); void g3(C3 auto...); void g4(C3 auto);
These declarations are functionally equivalent (but not equivalent) to the following declarations.
template<C1 T, C2 U> void g1(const T*, U&); template<C1... Ts> void g2(Ts&...); template<C3... Ts> void g3(Ts...); template void g4(T);
Abbreviated function templates can be specialized like all function templates.
template<> void g1(const int*, const double&);
— end example
]
An abbreviated function template can have a template-head.
The invented template-parameters are appended to the template-parameter-list after the explicitly declared template-parameters.
[ Example
:
template concept C = ;
template <typename T, C U> void g(T x, U y, C auto z);
This is functionally equivalent to each of the following two declarations.
template<typename T, C U, C W> void g(T x, U y, W z);
template<typename T, typename U, typename W> requires C && C void g(T x, U y, W z);
— end example
]
A function declaration at block scope shall not declare an abbreviated function template.
A declarator-id or abstract-declaratorcontaining an ellipsis shall only be used in a parameter-declaration.
When it is part of aparameter-declaration-clause, the parameter-declaration declares a function parameter pack ([temp.variadic]).
A function parameter pack is a pack expansion ([temp.variadic]).
[ Example
:
template<typename... T> void f(T (* ...t)(int, int));
int add(int, int); float subtract(int, int);
void g() { f(add, subtract); }
— end example
]
There is a syntactic ambiguity when an ellipsis occurs at the end of a parameter-declaration-clause without a preceding comma.
In this case, the ellipsis is parsed as part of theabstract-declarator if the type of the parameter either names a template parameter pack that has not been expanded or contains auto; otherwise, it is parsed as part of the parameter-declaration-clause.88
9.3.3.6 Default arguments [dcl.fct.default]
[ Note
:
Default arguments will be used in calls where trailing arguments are missing ([expr.call]).
— end note
]
[ Example
:
The declaration
void point(int = 3, int = 4);
declares a function that can be called with zero, one, or two arguments of typeint.
It can be called in any of these ways:
point(1,2); point(1); point();
The last two calls are equivalent topoint(1,4)andpoint(3,4), respectively.
— end example
]
A default argument shall not be specified for a template parameter pack or a function parameter pack.
If it is specified in aparameter-declaration-clause, it shall not occur within adeclaratororabstract-declaratorof aparameter-declaration.89
For non-template functions, default arguments can be added in later declarations of a function in the same scope.
Declarations in different scopes have completely distinct sets of default arguments.
That is, declarations in inner scopes do not acquire default arguments from declarations in outer scopes, and vice versa.
In a given function declaration, each parameter subsequent to a parameter with a default argument shall have a default argument supplied in this or a previous declaration, unless the parameter was expanded from a parameter pack, or shall be a function parameter pack.
[ Note
:
A default argument cannot be redefined by a later declaration (not even to the same value) ([basic.def.odr]).
— end note
]
[ Example
:
void g(int = 0, ...);
void f(int, int);
void f(int, int = 7);
void h() {
f(3);
void f(int = 1, int);
}
void m() {
void f(int, int);
f(4);
void f(int, int = 5);
f(4);
void f(int, int = 5);
}
void n() {
f(6);
}
template<class ... T> struct C {
void f(int n = 0, T...);
};
C c;
— end example
]
For a given inline function defined in different translation units, the accumulated sets of default arguments at the end of the translation units shall be the same; no diagnostic is required.
If a friend declaration specifies a default argument expression, that declaration shall be a definition and shall be the only declaration of the function or function template in the translation unit.
The default argument has the same semantic constraints as the initializer in a declaration of a variable of the parameter type, using the copy-initialization semantics ([dcl.init]).
The names in the default argument are bound, and the semantic constraints are checked, at the point where the default argument appears.
Name lookup and checking of semantic constraints for default arguments in function templates and in member functions of class templates are performed as described in [temp.inst].
[ Example
:
In the following code,gwill be called with the valuef(2):
int a = 1; int f(int); int g(int x = f(a));
void h() {
a = 2;
{
int a = 3;
g();
}
}
— end example
]
[ Note
:
In member function declarations, names in default arguments are looked up as described in [basic.lookup.unqual].
Access checking applies to names in default arguments as described in [class.access].
— end note
]
Except for member functions of class templates, the default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition; the program is ill-formed if a default constructor ([class.default.ctor]), copy or move constructor ([class.copy.ctor]), or copy or move assignment operator ([class.copy.assign]) is so declared.
Default arguments for a member function of a class template shall be specified on the initial declaration of the member function within the class template.
[ Example
:
class C { void f(int i = 3); void g(int i, int j = 99); };
void C::f(int i = 3) {}
void C::g(int i = 88, int j) {}
— end example
]
[ Note
:
A local variable cannot be odr-used ([basic.def.odr]) in a default argument.
— end note
]
[ Example
:
void f() {
int i;
extern void g(int x = i);
extern void h(int x = sizeof(i));
}
— end example
]
[ Note
:
The keywordthismay not appear in a default argument of a member function; see [expr.prim.this].
[ Example
:
class A {
void f(A* p = this) { }
};
— end example
]
— end note
]
A default argument is evaluated each time the function is called with no argument for the corresponding parameter.
A parameter shall not appear as a potentially-evaluated expression in a default argument.
Parameters of a function declared before a default argument are in scope and can hide namespace and class member names.
[ Example
:
int a;
int f(int a, int b = a);
typedef int I;
int g(float I, int b = I(2));
int h(int a, int b = sizeof(a));
— end example
]
A non-static member shall not appear in a default argument unless it appears as the id-expression of a class member access expression ([expr.ref]) or unless it is used to form a pointer to member ([expr.unary.op]).
[ Example
:
The declaration ofX::mem1()in the following example is ill-formed because no object is supplied for the non-static memberX::aused as an initializer.
int b;
class X {
int a;
int mem1(int i = a);
int mem2(int i = b);
static int b;
};
The declaration ofX::mem2()is meaningful, however, since no object is needed to access the static memberX::b.
Classes, objects, and members are described in [class].
— end example
]
A default argument is not part of the type of a function.
[ Example
:
int f(int = 0);
void h() {
int j = f(1);
int k = f();
}
int (*p1)(int) = &f; int (*p2)() = &f;
— end example
]
When a declaration of a function is introduced by way of ausing-declaration, any default argument information associated with the declaration is made known as well.
If the function is redeclared thereafter in the namespace with additional default arguments, the additional arguments are also known at any point following the redeclaration where theusing-declarationis in scope.
A virtual function call ([class.virtual]) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object.
An overriding function in a derived class does not acquire default arguments from the function it overrides.
[ Example
:
struct A {
virtual void f(int a = 7);
};
struct B : public A {
void f(int a);
};
void m() {
B* pb = new B;
A* pa = pb;
pa->f();
pb->f();
}
— end example
]