Question:
Is it considered acceptable to use default argument initializers both in a definition of a function (e.g., void foo(int x =10) {...}) as well as its declaration? Stroustrup, in his only example, does not, but it seems reasonable and conforms to the grammar, doesn’t it?
I’ve wondered about this because g++ (2.8.1) behaves strangely for member function definitions with default arguments. If they are actual ints (like 0) or global variables, it is fine, but if they are const ints, it complains about an inconsistency (!).
Answer:
You should specify default parameter values in the function’s prototype exclusively. The default values should not appear in the definition.
Note also that the declaration must be seen before you call the function. The One Definition Rule requires that repeated declarations of the same function must have the same default parameter values. Doing something like this:
//file first.cpp void f (int x = 0); //file second.cpp void f (int x = 1);
is illegal. Instead, you should declare the function with its default parameter values in a single .h file and #include that file in every source file that refers to that function.
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.
Related Posts
- Embarcadero Unveils RAD Solution Pack, the Complete VCL and FMX Component Solution for RAD Studio, Delphi and C++Builder
- Congress debates revival of Affordable Connectivity Program
- Identifying all the Index(s) Available on a Table in MySQL
- How AI is Shaping the Future of Student Learning
- G7 Unveils AI Code for Ethical Innovation






















