Lecture 6
Example
cin -> ifstream
input file stream
cin -> ifstream
input file streamcout -> ofstream
output file stream
cout -> ofstream
output file streamNote: Anywhere cin/cout is usable, an ifstream/ofstream is usable.
String Streams
An interface to interact with a string like it's a stream. Library: include <sstream>
Example: Convert int into a string
Example: Convert a string into a number
Example: print ints to cout, ignore non-ints
Why don't we need to clear and ignore iss?
Each iteration initializes its own istring stream.
What will the input "h3110" print?
Declare string and not initializing
Default function parameters
Example:
Example: Optional Parameters must be on the right (if it starts on the left, program will not compile) eg. (int x=5,int y) # will not compile
Overloading
Giving multiple functions to one function name in C++, but in C, you must only have unique function names Example in C:
Example in C++:
What is a valid overload?
Compiler looks at the number and types of parameters.
Based on params, decides the function to call (this decision is made at compile time)
Overloads must differ in number or types of args.
C++ does not overload on return type.
i.e. if two functions have the same name and params, but different return types
This is not valid because C++ only checks params
Must be no valid way to call function with same params including default params
does not compile if you call function without specifying default param, if it is specified, it will compile
Structures
Example:
This does not work:
Why not?
size of struct must be known when it is defined
struct is a recursive class, there is no pointer present - - when pointer is present, computer knows the size of the pointer, so it adds the size of a pointer and an int to get the size
Constants
Try to declare as many things const as possible
Parameter Passing
Pass-by-value: A copy of argument is used in the function
Why does cin >> x
alter x? Why not cin >> &x
?
C++ has another pointer-like type called References
References
References are like const pointers with automatic dereferencing.
Example:
In all cases, z behaves exactly like y. z is an alias to y -> it's another name for y
This is an l value reference:
l value: left value
must be initialized to something that can be on the left of an assigment
Last updated