Default Arguments in functions

Default Arguments in functions - #include...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Default Arguments in functions We saw in CS101 that we could overload functions so that we could use the same name to call different function bodies. The compiler distinguished between the different function by comparing the number and types of arguments. Using default arguments looks similar to using overloaded functions, but is not the same. Sometimes we want to have a default for one or more of the arguments for a given function. The syntax for a default argument is the following: <return type> <function name>(<argument list>); where argument list looks like: You may have more than one argument in the argument list. However, once you list an argument that has a default value, all proceeding arguments must have defaults listed also. Default Arguments in functions #include <iostream> #include <fstream>
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: #include &lt;string&gt; using namespace std; void printHeader(ostream &amp;fout=cout, int choice = 1); /*Note that the first parameter is of the type ostream not ofstream. cout is not of type ofstream, but of type ostream. Ofstream is derived (inherited) from ostream, so objects of the ofstream class can be passed to functions asking for an ostream object.*/ int main() { ofstream fout(&quot;test.txt&quot;); if(!fout) { cerr &lt;&lt; &quot;Unable to open output file\n&quot;; exit(1); } printHeader(fout,2); printHeader(fout); // Not Legal, If you want to specify a value for a //default value, you must supply values for all //preceding default variables. //printHeader(2); printHeader(); fout.close(); return 0; } void printHeader(ostream &amp;fout, int choice) { if(choice ==1) { fout &lt;&lt; &quot;No choice given&quot; &lt;&lt; endl; } else { fout &lt;&lt; &quot;hello, world&quot; &lt;&lt; endl; } }...
View Full Document

This note was uploaded on 04/18/2008 for the course CS 201 taught by Professor Markhieber during the Spring '08 term at University of Missouri-Kansas City .

Page1 / 2

Default Arguments in functions - #include...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online