{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Default Arguments in functions - #include<string>...

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: &ltreturn type> &ltfunction name>(&ltargument list>); where argument list looks like: &lttype name> &ltvariable name> [=&ltvalue>] 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 Document Right 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 <string> using namespace std; void printHeader(ostream &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("test.txt"); if(!fout) { cerr << "Unable to open output file\n"; 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 &fout, int choice) { if(choice ==1) { fout << "No choice given" << endl; } else { fout << "hello, world" << endl; } }...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

Default Arguments in functions - #include<string>...

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

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